Django:在查询集中过滤 get_foo_display [英] Django: Filter for get_foo_display in a Queryset
问题描述
我一直试图在一个简单的模型上过滤查询集,但到目前为止没有运气.
I've been trying to filter a queryset on a simple model but with no luck so far.
这是我的模型:
class Country(models.Model):
COUNTRY_CHOICES = (
('FR', _(u'France')),
('VE', _(u'Venezuela')),
)
code = models.CharField(max_length=2, choices=COUNTRY_CHOICES)
def __unicode__(self):
return self.get_code_display()
我想做一些类似的事情:
And I would like to do something like:
Country.objects.filter(get_code_display__icontains="france")
Country.objects.filter(code__display__icontains="france")
Country.objects.filter(get_code_display__icontains="france")
但以上这些都不起作用.如何过滤具有 choices
属性的字段?我认为覆盖的 __unicode__
会有所帮助,但我想我错过了一些东西.
But none of those above are working. How do you filter on a field that has a choices
attribute? I thought the overridden __unicode__
would help but I guess I'm missing something.
推荐答案
你不能这样做.filter
在数据库级别工作,数据库对您的长名称一无所知.如果要对某个值进行过滤,则需要将该值存储在数据库中.
You can't do this. filter
works at the database level, and the database doesn't know anything about your long names. If you want to do filtering on a value, you need to store that value in the database.
另一种方法是将值转换回代码,并对其进行过滤:
An alternative is to translate the value back into the code, and filter on that:
country_reverse = dict((v, k) for k, v in COUNTRY_CHOICES)
Country.objects.filter(code=country_reverse['france'])
这篇关于Django:在查询集中过滤 get_foo_display的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!