Darwin Tech
Darwin Tech

Reputation: 18919

Django append query results to query set

in a view I am constructing I need to consult multiple databases. What I want to do is use the results of on query_set to search another db table.

I have functioning mydb1_query_set, what I need now is something like this:

for row in mydb1_query_set:
        mydb2_query_set = Mytable.objects.filter(id=row.id)

So that I keep adding to the initially empty mydb2_query_set as I iterate. I realize that there is no QuerySet.append, so how do I achieve what I want? Any help much appreciated...

Upvotes: 7

Views: 34223

Answers (4)

DGideas
DGideas

Reputation: 69

Django's Managers object provide a default method called .get_queryset() which allow you to concatenate extra queries after it:

queryset = MyModel.objects.get_queryset()
if username:
    queryset = queryset.filter(username=username)
if country:
    queryset = queryset.filter(country=country)

You could easily using .query attribute getting the SQL, for example:

>>> print(queryset.query)
SELECT `myapp_mymodel`.`id`, `myapp_mymodel`.`username`, `myapp_mymodel`.`country` FROM `myapp_mymodel` WHERE `myapp_mymodel`.`country` = foo

Upvotes: 0

agrippa
agrippa

Reputation: 909

Using python's built in itertools module worked best for me.

from itertools import chain

qs1 = Mytable.objects.filter(id=2)
qs2 = Mytable.objects.filter(id=3)

all_queries = chain(qs1, qs2)

Here's the docs, in case you'd like some reference materials: https://docs.python.org/3/library/itertools.html#itertools.chain

Upvotes: 3

Maestro Pu
Maestro Pu

Reputation: 141

qs1= <QuerySet [<User: [email protected]>, <User: [email protected]>]>
qs2= <QuerySet [<User: [email protected]>, <User: [email protected]>]>
qs3 = qs1 | qs2

res:

qs3 = <QuerySet [<User: [email protected]>, <User: [email protected]>, <User:[email protected]>, <User: [email protected]>]>

EDIT: Link to documentation:

https://docs.djangoproject.com/en/2.1/ref/models/querysets/#operators-that-return-new-querysets

Upvotes: 14

Alasdair
Alasdair

Reputation: 308779

Use a list instead of a queryset, and then you can append or extend as you wish.

mydb2_query = []
for row in mydb1_query_set:
    mydb2_query.extend(list(Mytable.objects.filter(id=row.id)))

Upvotes: 13

Related Questions