2

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)
4
  • 1
    You can append them in a tuple. x.append((y,z)) Commented Jan 3, 2015 at 18:02
  • possible duplicate of How can I find the union of two Django querysets? Commented Jan 3, 2015 at 18:02
  • 1
    Looks like you want to chain them. Commented Jan 3, 2015 at 18:03
  • i dont want to combine them inside a filter query of a model, i need to do it using two variable x append y i plan to do it in a for loop Commented Jan 3, 2015 at 18:09

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You need chain.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.