首页 > 解决方案 > 如何在 Django 模板中迭代抽象类的对象?

问题描述

我有一个抽象类 Item 和多个继承自 Item 的产品类。在我的模板中,我想要从 Item 继承的每个类的 for 循环,但我不想为从 Item 继承的每个类重写 for 循环。我想要类 Item 的 for 循环,它将给我从 Item 继承的每个子类。

标签: python-3.xdjangodjango-modelsdjango-viewsdjango-templates

解决方案


一种方法,您可以通过 itertools.chain 合并所有查询集

# views.py
import itertools
def handle(request):
    all_products = itertools.chain(qset_a, qset_b, qset_c)
    context = {'all_products':all_products}
    return render(request, 'template.html', context)

推荐阅读