问题描述
我的模型为零售商指定了一个类别-例如-沃尔玛"
My model has a category for a retailer--example - "Walmart"
我数据库中的所有零售商均已输入首字母大写.
All of the retailers in my database have been entered with the first letter capitalized.
我试图在我的网站上显示零售商的产品列表.
I am trying to show a list of products by retailer on my site.
我的网址看起来像这样:
My url looks like so:
path('retailer-deals/<str:retailer>', deals_by_retailer, name='retailer'),
我的看法如下:
def deals_by_retailer(request,retailer):
retailer_deals = Deal.objects.filter(retailer__company=retailer).order_by('expired','-date_added')
retailer = retailer
return render(request, 'deals/deal_by_retailer.html', {'retailer_deals': retailer_deals, 'retailer': retailer})
因此,如果我转到 retailer-deals/walmart
,则不会显示任何内容...
So if i go to retailer-deals/walmart
nothing shows up...
但是当然 retailer-deals/Walmart
可以正常工作
我可能很挑剔-但我认为使用小写的 walmart
看起来更专业,以防万一有人输入大写版本,我想确保它可以正确填充
i might be being nitpicky--but i think it looks more professional with the lower case walmart
and just in case someone goes to enter the uppercase version, i want to make sure it populates correctly
我确实看到有人提到(?i)类似问题,
I did see someone mention a (?i) for a similar problem,
,我尝试将路径更改为此:
and i tried changing my path to this:
path('(?i)retailer-deals/< str:retailer>',Deals_by_retailer,name ='retailer'),
但这似乎不起作用....而且,如果我要列出具有相关链接的零售商,则生成的url仍将具有大写的url.
but that doesn't seem to work....and also, if i go to list the retailers with associated links--the generated url will still have the uppercase url..
推荐答案
您可以使用 iexact ,不区分大小写的完全匹配.
You can use iexact in your filter, A case-insensitive exact match.
retailer_deals = Deal.objects.filter(
field_name__iexact=retailer).order_by('expired','-date_added')
正如许多其他人所建议的那样,最好的方法是对子弹进行此类查询,因此您将:
As many of other people suggest,the best way is to do such query with slug, so you would have:
from django.template.defaultfilters import slugify
import uuid
class YourModel(mdoels):
slug = models.SlugField()
name = models.CharField(max_mength=100)
# override the save method to have slug automatically generated
def save(self, *args, **kwargs):
if self.pk is None:
slug = slugify(self.name)
while self.__class__.objects.filter(slug=slug).exists():
slug = "%s-%s" % (slug,str(uuid.uuid4())[:5])
self.slug = slug
super(YourModel, self).save(*args, **kwargs)
您的网址将变为:
path('retailer-deals/<slug:slug>', deals_by_retailer, name='retailer'),
和您的观点:
def deals_by_retailer(request,slug):
retailer_deals = Deal.objects.filter(retailer__slug=slug)
''' codes '''
这篇关于在Django中以小写形式显示URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!