如何在Django模板中限制与外键相关的对象集合?
给出了一个名为“comment”的模型,该模型与名为“task”的模型具有外键关系 将此限制为5条评论的最佳方式是什么,如:如何在Django模板中限制与外键相关的对象集合?,django,django-templates,Django,Django Templates,给出了一个名为“comment”的模型,该模型与名为“task”的模型具有外键关系 将此限制为5条评论的最佳方式是什么,如: Entry.objects.all()[:5] 你没有。你不应该在一个模板中做“真正的工作”,这会破坏规则 在视图中执行实际工作,并将数据传递给模板(使用上下文字典) 然后,您可以迭代模板中的注释: {% for task, task_comments in comments.items %}{{ task }}{% endfor %} 谢谢,这个也行。哪种方法更好?
Entry.objects.all()[:5]
你没有。你不应该在一个模板中做“真正的工作”,这会破坏规则 在视图中执行实际工作,并将数据传递给模板(使用上下文字典) 然后,您可以迭代模板中的注释:
{% for task, task_comments in comments.items %}{{ task }}{% endfor %}
谢谢,这个也行。哪种方法更好?有很多django模板标记/过滤器允许对数据进行如此轻微的操作,因此我不会看到有如此大的违反mvc概念的情况,django对该概念也有稍微不同的方法:
def handle_comments(request):
tasks = Task.objects.all()
comments = {}
for task in tasks:
comments[task] = task.comment_set.all()[:5]
return render_to_response('commenting.html', {'comments': comments})
{% for task, task_comments in comments.items %}{{ task }}{% endfor %}
{% for task in tasks %}
{% for comment in task.comment_set.all|slice:"5" %}
{{ comment }}
{% endfor %}
{% endfor %}