【发布时间】: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 循环时选择一个外键?
【问题讨论】:
-
您没有将
in_country导入到您的模板中。你需要使用{% load file_that_defined_in_country %}来加载过滤器:docs.djangoproject.com/en/1.9/howto/custom-template-tags
标签: django django-templates django-queryset