-
-
Save quevon24/3fd316b7ddbc4d862cb7dacc69f5da94 to your computer and use it in GitHub Desktop.
Combine two querysets from different models in Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
from blog.models import BlogEntry | |
from news.models import NewsEntry | |
def get_fresh_news_and_blog_entries(): | |
u"""Returns a list containing published news entries and blog posts mixed, | |
sorted by publish date. Suitable for template context of, say, landing page. | |
""" | |
news = list(NewsEntry.objects. | |
filter(publish_on__lt=datetime.datetime.now()). | |
order_by('-publish_on')) | |
blog = list(BlogEntry.objects. | |
filter(publish_on__lt=datetime.datetime.now()). | |
order_by('-publish_on')) | |
return sorted(news + blog, key=lambda item: item.publish_on, reverse=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment