开发者

how can I filter on the second element in a tuple of tuples?

开发者 https://www.devze.com 2022-12-12 04:17 出处:网络
In my model I have a field: country = models.CharField(_(\'Country\'), max_length=2, choices=COUNTRIES)

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?


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])
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号