Valchris
Valchris

Reputation: 1481

Concat results of querySet into one list

I have a model X, containing a ManyToManyField Y, I'm trying to concatenate the results of a querySet of X's into a list of all the entries in Y

I know the "easy" way would be:

for x in X:
    for y in x.Y.all():
        list.append(y)

The reasoning to this is related to my previous question: If x in <listOfModels.field> syntax

Thanks in advance,

Upvotes: 2

Views: 1710

Answers (3)

Daniel Roseman
Daniel Roseman

Reputation: 599480

Turn the query around. You're interested in Ys, so you should query Ys.

y_list = Y.objects.filter(x__in=X)

Upvotes: 0

jdi
jdi

Reputation: 92559

You could try chaining together the queryset objects into a concatenated generator:

chained = itertools.chain(*[x.Y.all() for x in X])
print chained
# <itertools.chain object at 0x10100eb90>

for y in chained:
    print y

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239240

Use itertools.chain:

from itertools import chain

chain(SomeModel.objects.all(), OtherModel.objects.all(), ...)

Just bear in mind that chain returns an iterable, which means you can then use it in for loops and such but you can't filter the QuerySets further or do normal list operations.

Upvotes: 3

Related Questions