django模板获取queryset的外键

时间:2016-01-12 22:55:40

标签: django django-templates django-queryset

我的django app中有这些模型:

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 %}

我希望根据name打印GeoBonus country。假设用户的国家/地区是字符串。

{% 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循环时选择一个外键

1 个答案:

答案 0 :(得分:1)

这个问题与外键或查询集没有任何关系。该错误告诉您到底出了什么问题:它无法识别“in_country”过滤器。

由于upper无效,因此“加载模板标记”的断言完全不遵循:upper是由Django本身提供的内置过滤器,而in_country则不是。{% load module_that_defines_filter %}。您需要先使用<div ng-repeat="entry in entries > <div ng-if="entry.pay.length>1"> <div ng-repeat="item in entry.pay"> <span>{{entry.uuid}}</span> <span>{{item.number}}</span> </div> </div> </div> 加载模板标记库,然后才能使用它。