Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 915
jtheoof Avatar asked Jan 18 '11 17:01

jtheoof


People also ask

How do I do a not equal in Django QuerySet filtering?

To do a not equal in Python Django queryset filtering, we can negate a equal with ~ . to call filter with the Q object negated with ~ to return all the Entry results that don't have id 3.

What does QuerySet filter return?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.


2 Answers

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'])
like image 84
Daniel Roseman Avatar answered Sep 30 '22 16:09

Daniel Roseman


You can use Choices

from model_utils import Choices

class Country(models.Model):
    COUNTRY_CHOICES = Choices((
        ('FR', _(u'France')),
        ('VE', _(u'Venezuela')),
    ))

    code = models.CharField(max_length=2, choices=COUNTRY_CHOICES)

And make a query:

Country.objects.filter(code=Country.COUNTRY_CHOICES.france)
like image 38
Daniil Mashkin Avatar answered Sep 30 '22 18:09

Daniil Mashkin