Skip to content

Instantly share code, notes, and snippets.

@strogonoff
Created June 13, 2014 08:53
Show Gist options
  • Save strogonoff/d029940040009628280f to your computer and use it in GitHub Desktop.
Save strogonoff/d029940040009628280f 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