Vahid Kharazi
Vahid Kharazi

Reputation: 6033

Sum two query set in django

I have two models, Quote and Post. I want two send this to my template:

posts = Post.objects.order_by("-submitted_time")
quotes = Quote.objects.order_by("-submitted_time")

thing = posts + quotes

but some of two QuerySet not support. How can I send posts and quote to the template?

suppose I have two Post and two Quote in database like this:

   post 1        submitted_time:2010/2/12
   post 2        submitted_time:2010/2/8 
   quote 1       submitted_time:2010/2/9
   quote 2       submitted_time:2010/2/13

I want to send a list like [quote2, post1, quote1, post2]

Upvotes: 0

Views: 968

Answers (1)

karthikr
karthikr

Reputation: 99620

You can do:

from itertools import chain
thing = list(chain(posts, quotes))

To order it the way you want:

import operator
from itertools import chain

thing = list(chain(posts, quotes))
thing = sorted(thing, key=operator.attrgetter('submitted_time', reverse=True)

Or

thing = sorted(thing, key=operator.attrgetter('submitted_time')

depending on which you want

Upvotes: 2

Related Questions