Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quevon24/3fd316b7ddbc4d862cb7dacc69f5da94 to your computer and use it in GitHub Desktop.
Save quevon24/3fd316b7ddbc4d862cb7dacc69f5da94 to your computer and use it in GitHub Desktop.
Combine two querysets from different models in Django
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