我有类似的东西:
{% 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对象的任何想法?
答案 0 :(得分:2)
你可以为此写一个custom template tags,这就像:
在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 }}
答案 1 :(得分:0)
答案 2 :(得分: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 }}