1

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.

coderDcoder
  • 585
  • 3
  • 16

1 Answers1

2

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

Hafnernuss
  • 2,659
  • 2
  • 29
  • 41
  • Could you please tell me how I can do it when there are overlapping fields(say `number` for both a and b)? I don't really quite understand the link you have sent me. Moreover, is it possible for the "overlapping fields" to be datetime or datefields but simply have different field labels in the model? – coderDcoder Dec 07 '21 at 12:32
  • Maybe, update your question to include both your models. Otherwise it's hard to say what you want to achieve. – Hafnernuss Dec 07 '21 at 13:01