BOMBOLOM.COM

(django) Concatenate QuerySets

Posted by José Lopes

In some situations you may want to concatenate two QuerySets.

The solution depends whether the QuerySets have the same model or not, and this post shows both solutions.

The information presented was based on this thread.

If you have the same model, for instance:

query_1 = Model_1.objects.filter(id=1) 
query_2 = Model_1.objects.filter(id=2)

You can concatenate them using | (for union) or & (for intersection).

The result would be something like:

query_1 | query_2 = [, ]
query_1 & query_2 = []

In this case the final result is still a QuerySet so we can use any built-in Django feature.

On the other hand, if you are concanetating QuerySets with different model, like:

query_1 = Model_1.objects.filter(id=1) 
query_2 = Model_2.objects.filter(id=1)

The case can be solved using the python iterator itertools.

Here is how to use it:

import itertools
for record in itertools.chain(query_1,query_2):
    do_something(record)

The do_something function can be whatever you need. A common case is to join the two queries result in one single list, for instance:

import itertools
record_list = []
for record in itertools.chain(query_1,query_2):
    record_list.append(record)

Once doing this the result is no longer a QuerySet but a List, loosing all the possible nice features that Django provides like for instance the dictsort on the templates.

So how can we sort the result list by some specific model field (assuming it exists in both models), like for instance the start_date. The solution would be:

record_list.sort(key=lambda x: x.start_date)
2009.02.06 | There's more... | Comments 0 | Tags ,

Deixe a sua mensagem:

Nome:


E-mail:


URL:


Comment:

Secret number

To send you comment you must insert the "secret number" on the box


Made with PyBlosxom | Add to Google