Merging Querysets in Django

13 Jul 2009  •  Comments

I had a need in one of my projects to do two different queries that result in similarly structured data. Instead of passing two variables into the template and then having to worry about the logic on the template side I wanted to merge them.

Thankfully Python provides a solution:

from itertools import chain

list = Model.objects.filter(foo=foo)
list2 = Model2.objects.filter(foo=foo)

final_var = list(chain(list,list2))

final_var is now a list containing both sets of results.

UPDATE:  While the above does work you can also use a much simpler |

final_var = list | list2

Thanks foresmac!

Twitter Facebook Stumbleupon Reddit Digg

Copyright © 2004 - 2013 Nomad.Works | Made in Ottawa