在我的模型中,我有一个字段:
country = models.CharField(_('Country'), max_length=2, choices=COUNTRIES)
其中 COUNTRIES 是这样的元组的元组:
COUNTRIES = (
('AF', _('Afghanistan')),
...等等
现在我想按国家/地区名称过滤该模型的实例。
这个:
i = MyModel.objects.filter(country__iexact=query)
只允许我按国家/地区代码进行过滤。
如何按国家/地区名称过滤?
最佳答案
您无法直接按国家/地区名称进行过滤(选项
仅在用户界面中使用,而不在数据库中使用)。
如果您获得全名作为输入,请在 COUNTRIES
元组中查找代码。例如:
# ... 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])
关于python - 如何过滤元组中的第二个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1745919/