Django:在Queryset中过滤get_foo_display

jth*_*oof 12 python django filter django-queryset choicefield

我一直试图在一个简单的模型上过滤一个查询集但到目前为止没有运气.

这是我的模型:

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()
Run Code Online (Sandbox Code Playgroud)

我想做的事情如下:

Country.objects.filter(get_code_display__icontains="france")
Country.objects.filter(code__display__icontains="france")
Country.objects.filter(get_code_display__icontains="france")
Run Code Online (Sandbox Code Playgroud)

但以上都没有奏效.如何过滤具有choices属性的字段?我认为被覆盖的__unicode__会有所帮助,但我想我错过了一些东西.

Dan*_*man 22

你不能这样做.filter在数据库级别工作,数据库对您的长名称一无所知.如果要对值进行过滤,则需要将该值存储在数据库中.

另一种方法是将值转换回代码,并对其进行过滤:

country_reverse = dict((v, k) for k, v in COUNTRY_CHOICES)
Country.objects.filter(code=country_reverse['france'])
Run Code Online (Sandbox Code Playgroud)

  • django可以做些什么来使它更容易一些.我认为这将是一个常见的操作 (5认同)