byrdr
byrdr

Reputation: 5467

Django chaining multiple queries together to return latest

I have 3 separate models. I would like to be able to do a query on all tables and return the object with the latest date. What would be the best approach for this? I currently have them returned in a chain. All of the models contain an auto_now_add DateTimeField. Is it possible to filter the latest created object based on the chained queryset?

article_list = Article.objects.all()
issue_list = Issue.objects.all()
annual_list = Annual.objects.all()

result_list = list(chain(article_list, issue_list, annual_list))

Upvotes: 0

Views: 119

Answers (1)

user2717954
user2717954

Reputation: 1902

if you want only 1 object you can use max() with key

max(result_list, key=lambda x: x.date) #or whatever the name of the field is (should be same on all models)

on the same fashion if you want the whole list sorted by the date field you can use sorted() and give the above key

Upvotes: 1

Related Questions