【问题标题】:How to iterate over an abstract class's objects in a Django template?如何在 Django 模板中迭代抽象类的对象?
【发布时间】:2020-10-17 19:40:42
【问题描述】:

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

【问题讨论】:

    标签: python-3.x django django-models django-views django-templates


    【解决方案1】:

    其中一种方法,您可以通过 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)
    

    【讨论】:

    • 我在尝试时遇到 TypeError('ModelBase' 对象不可迭代)。我用我的一个子类的名称替换了 qset_a。
    • qset_a 应该是查询集,如 Product.objects.all() 或 filter(),而不是 Product
    • 谢谢,它有效。现在,有没有一种方法可以将 models.py 中的所有对象链接起来,而不必担心每次添加新模型时都会添加新查询集?
    猜你喜欢
    • 2021-10-30
    • 2019-09-02
    • 2012-08-10
    • 1970-01-01
    • 2021-01-27
    • 2019-11-15
    • 2013-12-16
    • 2014-10-18
    • 2017-12-23
    相关资源
    最近更新 更多