Django:在Queryset中过滤get_foo_display [英] Django: Filter for get_foo_display in a Queryset
问题描述
这是我的模型:
$ b $我已经尝试过滤一个简单的模型上的查询,但没有运气。 b class国家(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()
而且想做一些类似的事情:
Country.objects.filter(get_code_display__icontains =france)
Country.objects .filter(code__display__icontains =france)
Country.objects.filter(get_code_display__icontains =france)
但是上面没有一个是正常的。如何过滤具有选择
属性的字段?我认为覆盖的 __ unicode __
将有所帮助,但我想我错过了一些。
你不能这样做。 过滤器
在数据库级别工作,数据库不知道您的长名称。如果要对某个值进行过滤,则需要将该值存储在数据库中。
另一种方法是将值转换回代码,然后过滤那个:
country_reverse = dict((v,k)for k,v in COUNTRY_CHOICES)
Country.objects。 filter(code = country_reverse ['france'])
I've been trying to filter a queryset on a simple model but with no luck so far.
Here is my model:
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")
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.
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:在Queryset中过滤get_foo_display的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!