How to display instances from two different django models in one template inside the same table?

In the django application, I created different models, and everything looks fine until I try to use data from two different models inside the same table. To summarize: on the main page, I need to create a table containing data from both models, sorted by date.

The two models I need to display are as follows.

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

Then I tried to create a view that would allow me to work with different models.

This is my 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

Now, how can I create a table inside a template that shows both models at once, ordering each record by the date of validity (regardless of whether this record belongs to a program or document)?

Thank you in advance!

+4
2

, ( ), , 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 , .

, !

+1
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
0

Source: https://habr.com/ru/post/1686394/


All Articles