【问题标题】:how can I filter on the second element in a tuple of tuples?如何过滤元组元组中的第二个元素?
【发布时间】:2009-11-17 00:49:17
【问题描述】:

在我的模型中,我有一个字段:

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

COUNTRIES 是这样的元组的元组:

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

...等等

现在我想按国家/地区名称过滤该模型的一个实例。

这个:

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

只允许我按国家代码过滤。

如何按国家/地区名称过滤?

【问题讨论】:

  • 我认为你在那里遗漏了一些代码。你能告诉我查询是在哪里定义的吗?
  • In q = request.GET['q'].lower() 但这无关紧要,我也可以在示例中硬编码一个字符串,例如: i = MyModel.objects.filter(country__iexact= '阿富汗')

标签: python django filter country


【解决方案1】:

您不能直接按国家/地区名称进行过滤(choices 仅在 UI 中使用,而不在数据库中使用)。

如果您将全名作为输入,请在 COUNTRIES tuple-of-tuples 中查找代码。例如:

# ... 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])

【讨论】:

  • 嗯,我试过这个,但我得到了一个异常类型:KeyError,country_to_id_dict 看起来像这样:{: 'AF', : 'AL', ... 等等。也许是因为每个元组中的第二个元素是可翻译的文本,因为: from django.utils.translation import ugettext_lazy as _
  • 好的,对 country_to_dict 的小修改起作用了: country_to_id_dict = dict((t[1][:], t[0]) for t in COUNTRIES) 谢谢。最好使这种大小写不敏感(查询在其他地方折叠为小写): country_to_id_dict = dict((t[1][:].lower(), t[0]) for t in COUNTRIES)
猜你喜欢
  • 2013-04-29
  • 2022-11-04
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多