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)
Alasdair
  • 298,606
  • 55
  • 578
  • 516
Sprig Mendle
  • 567
  • 1
  • 6
  • 12
  • 1
    You can append them in a tuple. _x.append((y,z))_ –  Jan 03 '15 at 18:02
  • possible duplicate of [How can I find the union of two Django querysets?](http://stackoverflow.com/questions/4411049/how-can-i-find-the-union-of-two-django-querysets) – garnertb Jan 03 '15 at 18:02
  • 1
    Looks like you want to [chain them](http://stackoverflow.com/a/796381/846892). – Ashwini Chaudhary Jan 03 '15 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 – Sprig Mendle Jan 03 '15 at 18:09

2 Answers2

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.

knbk
  • 52,111
  • 9
  • 124
  • 122
1

You need chain.

from itertools import chain
x = list(chain(x, y, z))
torm
  • 1,486
  • 15
  • 25