2

In my model I have a field:

   country = models.CharField(_('Country'), max_length=2, choices=COUNTRIES)

Where COUNTRIES is a tuple of tuples like this:

COUNTRIES = (
    ('AF', _('Afghanistan')),

... and so on

Now I want to filter an instance of that model, by the country name.

This:

   i = MyModel.objects.filter(country__iexact=query)

only lets me filter by the country code.

How can I filter by country name?

ria
  • 7,198
  • 6
  • 29
  • 35
  • I think you're missing a bit of code there. Can you show me where query gets defined? – Bryan McLemore Nov 17 '09 at 00:51
  • In q = request.GET['q'].lower() but that's irrelevant, I could as well hardcode a string in the example, like: i = MyModel.objects.filter(country__iexact='Afganistan') – ria Nov 17 '09 at 01:31

1 Answers1

4

You cannot filter directly by the country name (the choices are only used in the UI, not in the database).

If you get the full name as an input, lookup the code in the COUNTRIES tuple-of-tuples. For example:

# ... initialize a lookup dictionary
country_to_id_dict = dict((t[1], t[0]) for t in COUNTRIES)

# ... use the dictionary in the query
i = MyModel.objects.filter(country__exact=country_to_id_dict[query])
codeape
  • 97,830
  • 24
  • 159
  • 188
  • Hmm, I tried this, but I get a Exception Type: KeyError with the country_to_id_dict looking somehow like this: {: 'AF', : 'AL', ... and so on. Maybe its because the second element in each tuple is a translatable text, because: from django.utils.translation import ugettext_lazy as _ – ria Nov 17 '09 at 01:22
  • 1
    OK, a minor modification of country_to_dict worked: country_to_id_dict = dict((t[1][:], t[0]) for t in COUNTRIES) Thanks. Even better to maek this case insensitive (the query is folded to lowercase elsewhere): country_to_id_dict = dict((t[1][:].lower(), t[0]) for t in COUNTRIES) – ria Nov 17 '09 at 01:43