Sprig Mendle
Sprig Mendle

Reputation: 597

How to append multiple filter() queries into one variable

If I have three different queries of a model how do i append them into one variable

x = AnswerModel.objects.filter(user= 'tim')

y = AnswerModel.objects.filter(user= 'paul')

z = AnswerModel.objects.filter(question= 'i like jam')

x = x.append(y)
x = x.append(z)

Upvotes: 2

Views: 2933

Answers (2)

knbk
knbk

Reputation: 53699

Use |:

x = AnswerModel.objects.filter(user= 'tim')
y = AnswerModel.objects.filter(user= 'paul')
z = AnswerModel.objects.filter(question= 'i like jam')

qs = x | y | z

Or, using django.db.models.Q:

x = AnswerModel.objects.filter(Q(user='tim') | Q(user='paul') | Q(question='i like jam')

Both methods will return all results from all querysets in a single queryset.

Upvotes: 3

torm
torm

Reputation: 1546

You need chain.

from itertools import chain
x = list(chain(x, y, z))

Upvotes: 1

Related Questions