【问题标题】:django template get foreign key of querysetdjango模板获取查询集的外键
【发布时间】:2016-04-17 18:10:52
【问题描述】:

我的 django 应用中有这些模型:

class GeoBonus(models.Model):
name = models.CharField(max_length=250)
country = models.ForeignKey(Country, related_name='geo_bonuses')
bookmaker = models.ForeignKey(Bookmaker, related_name='geo_bonuses')

Country 和 Bookmaker 中的属性并不重要,假设每个属性都有 name 参数。
在模板中,我有一个 for 循环:

{% for bookmaker in bookmakers %}
    {{bookmaker.name}}
{% endfor %}

我想打印基于country 的 GeoBonus 的name。假设用户的国家是一个字符串。

{% for bookmaker in bookmakers %}
    {{bookmaker.name}}
    {% if country_code %}
        {% for geo_bonus in bookmaker.geo_bonuses|in_country:country_code %}
            {{geo_bonus}}
        {% endfor %}
    {% endif %}
{% endfor %}

这是我的过滤器:

@register.filter
def in_country(qs, country_code):
    return qs.filter(country__twocode=country_code)

country_code 是通过视图发送的:

context = RequestContext(request,{
        'bookmakers': Bookmaker.objects.select_related('geo_bonuses').all(),
        'country_code': country_code,
    })

但这不起作用。我究竟做错了什么?我得到Invalid filter: 'in_country'(如果我使用简单的过滤器作为upper 字符串,它可以工作,所以模板标签被加载)。

所以基本上我的问题是,如何在运行 for 循环时选择一个外键

【问题讨论】:

标签: django django-templates django-queryset


【解决方案1】:

这个问题与外键或查询集无关。该错误准确地告诉您出了什么问题:它无法识别“in_country”过滤器。

您关于“模板标签已加载”的断言根本不符合 upper 工作:upper 是 Django 本身提供的内置过滤器,而 in_country 不是。您需要使用{% load module_that_defines_filter %} 加载您的模板标签库,然后才能使用它。

【讨论】:

  • 你是对的。但是我的模板中确实有 {% name_of_file %} 并且文件夹确实包含 __init__.py 文件,这很奇怪。
  • 我不明白你的评论。您需要实际致电load
  • 我确实调用了加载。然而我又犯了一个愚蠢的错误。我在另一个应用程序中有同名文件。这就是问题所在。感谢您的帮助!
猜你喜欢
  • 2011-09-01
  • 2015-03-09
  • 2021-09-20
  • 2015-01-25
  • 1970-01-01
  • 2012-12-27
  • 2018-12-20
  • 1970-01-01
  • 2013-09-27
相关资源
最近更新 更多