I am using the Django REST Framework in a project and I want to create a union of two different models.
My models
class A(models.Model):
name = models.CharField(max_length=240, blank=True)
geometry = models.GeometryField(blank=True, null=True)
abwrapper= models.ForeignKey(ABWrapper)
class Meta:
db_table = 'tbl_a'
class B(models.Model):
name = models.CharField(max_length=240, blank=True)
link = models.IntegerField(blank=True, null=True)
geometry = models.GeometryField(blank=True, null=True)
abwrapper= models.ForeignKey(ABWrapper)
class Meta:
db_table = 'tbl_b'
I am trying to create this request
SELECT id,name FROM tbl_a UNION (SELECT b.id,b.name From tbl_b b)
My attempt to unite
a = A.objects.values_list('id')
b = B.objects.values_list('id')
queryset = a | b
Error:
AssertionError: Cannot combine queries on two different base models.
Now I tried with the original model this way
class ABWrapper(models.Model):
objects = models.GeoManager()
class Meta:
db_table = u'ab_wrapper'
Added this model as ForeignKey above both models.
a = ABWrapper.objects.filter(a__isnull=False).values('a__id')
b = ABWrapper.objects.filter(b__isnull=False).values('b__id')
queryset = a | b
Error:
TypeError: Merging 'GeoValuesQuerySet' classes must involve the same values in each case.
Another attempt to make an alias
a = ABWrapper.objects.filter(a__isnull=False).extra(select={'tempID':'a__id'}).values_list('tempID')
b = ABWrapper.objects.filter(b__isnull=False).extra(select={'tempID':'b__id'}).values_list('tempID')
queryset = a | b
Error:
ValueError: When merging querysets using 'or', you cannot have extra(select=...) on both sides.
I searched on it, basically answered this problem as using a list for both models. But I do not want to use a list since I am using the Django Rest Framework, so I need a QuerySet. So my question is, if I use a list to combine, can I convert the resulting list to a QuerySet.
Note: I do not want to use SQL Query in Django
Is there any other way to accomplish this task?