【问题标题】:How to display instances from two different django models on the same template, inside the same table?如何在同一个模板内的同一个表中显示来自两个不同 django 模型的实例?
【发布时间】:2017-09-26 09:03:28
【问题描述】:

在一个 django 应用程序中,我创建了不同的模型,一切看起来都很好,直到我尝试在同一个表中使用来自两个不同模型的数据。 总结一下:在主页中,我需要创建一个表,其中包含两个模型的数据,按日期排序。

我需要展示的两个模型如下。

models.py

class Document(models.Model):
    number = models.CharField(max_length=10)
    description = models.CharField(max_length=50)
    assigned = models.BooleanField
    validity_date = models.DateField
    is_issued = models.BooleanField

class Program(models.Model):
    name = models.CharField(max_length=25)
    description = models.CharField(max_length=100)
    validity_date = models.DateField

然后,我尝试创建一个允许我使用不同模型的视图。

这是我的view.py:

class BaseView(generic.ListView):
    template_name = 'base/base_list.html'
    context_object_name = 'base_list'

    def get_queryset(self):
         queryset = Document.objects.order_by('due_date')
         return queryset

    def get_context_data(self, **kwargs):
        context = super(BaseView, self).get_context_data(**kwargs)
        context['Programs'] = Program.objects.all()
        context['Employees'] = Employee.objects.all()
        return context

现在我如何在模板中创建一个同时显示两个模型的表格,按有效日期对每个条目进行排序(无论条目属于程序还是文档)?

提前谢谢你!

【问题讨论】:

    标签: python django django-views


    【解决方案1】:

    您需要首先查询两个模型,将它们链接在一起(连接它们),然后按它们的共享属性排序,即validity_date。你可以这样做:

    from itertools import chain
    documents = Documents.objects.all()
    programs = Program.objects.all()
    final_combined_list = sorted(chain(documents,programs),key=lambda instance: instance.validity_date)
    

    您现在可以简单地将final_combine_list 传递给模板并渲染它以按照您想要的方式显示它。

    【讨论】:

      【解决方案2】:
      def get_context_data(self, **kwargs):
          context = super(BaseView, self).get_context_data(**kwargs)
          context['object_list'] = sorted(
              itertools.chain(Document.objects.all(), Program.objects.all()),
              key=lambda x: x.validity_date
          )
          return context
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-07
        • 1970-01-01
        • 2011-03-25
        • 2023-02-05
        • 2017-09-01
        • 2019-09-11
        • 1970-01-01
        • 2012-07-01
        相关资源
        最近更新 更多