How to create list of object from 2 models with sorting in Django?

I have this model in Django:

Class SmallNews(models.Model):
date_news = modeles.DateField
...

Class BigNews(models.Model):
date_news = modeles.DateField
...

I want to create list of object(SmallNews + BigNews) and sorting all this objects by DateField. What the best way to do this?

You can get the two querysets and then merge them into one using chain from itertools. Then you can sort the new list based on the date_news field. Something like:

from itertools import chain

small_news = SmallNews.objects.all()
big_news = BigNews.objects.all()

combined_news = chain(small_news, big_news)

sorted_news = sorted(combined_news, key=lambda news: news.date_news)
Back to Top