0

我有类似的东西:

{% for mother in mothers_list %}
    {% for father in fathers_list %}
        {% Child.objects.get(mother=mother, father=father) as child %}
            child.name

不幸的是,我不能使用模板中的参数调用函数,所以这一行

{% Child.objects.get(mother=mother, father=father) as child %}

不会工作。关于如何每次获取 Child 对象的任何想法?

4

3 回答 3

2

您可以为此编写自定义模板标签,如下所示:

在你的project/templatetags/custom_tags.py

    from django.template import Library
    register = Library()
    @register.filter
    def mother_father(mother_obj, father_obj):
            // Do your logic here
            // return your result 

在模板中,您使用模板标签,例如:

{% load custom_tags %}

{% for mother in mothers_list %}
    {% for father in fathers_list %}
        {{ mother|mother_father:father }}
于 2011-08-29T00:42:32.410 回答
0

阅读https://docs.djangoproject.com/en/dev/howto/custom-template-tags/并编写自定义标签。

于 2011-08-28T22:50:45.170 回答
0

您可以在视图函数中进行此处理。

在views.py中:

children_list = []
for mother in mothers_list:
    for father in fathers_list:
        try:
            child = Child.objects.get(mother=mother, father=father)
        except Child.DoesNotExist:
            child = None
        children_list.append(child)

然后在您的模板中:

{% for c in children_list %}
    {{ c.name }}
于 2011-09-01T20:59:53.917 回答