Created
June 13, 2014 08:53
-
-
Save strogonoff/d029940040009628280f 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