Home > other >  How do you combine two querysets into one queryset(not a list) in django?
How do you combine two querysets into one queryset(not a list) in django?

Time:12-08

I want to simply combine two querysets from different models into one queryset (and not a list as shown in other stackoverflow questions!). For example, here are two querysets:

a = Modelone.objects.all()
b = Modeltwo.objects.filter(number__gte=4)

Then, I want a queryset c that combines both a and b. Thank you, and please leave me any questions you have.

CodePudding user response:

You cannot do that. Imagine the following:

class Modelone(models.model):
 number = models.IntegerField()

class Modeltwo(models.model):
 text = models.TextField()

Imagine you would filter against your joined queryset, how can that work if the rows (or instances) do not have the same fields?

If you would want to join two querysets of the same model, you could do that:

qs1 = modelone.objects.filter(nummber=10)
qs2 = modelone.objects.filter(nummber=20)
joined = qs1 | qs2

(source)

If your two models are similar and have overlapping fields, you could use something like django-polymorphic

  • Related