【发布时间】:2014-05-31 09:32:44
【问题描述】:
我在项目中使用 Django REST Framework,我想创建两个不同的模型。
我的模型
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'
我正在尝试创建此查询
SELECT id,name FROM tbl_a UNION (SELECT b.id,b.name From tbl_b b)
我的联合尝试
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.
现在我用这种方式尝试了父模型
class ABWrapper(models.Model):
objects = models.GeoManager()
class Meta:
db_table = u'ab_wrapper'
将此模型添加为两个模型上方的 ForeignKey
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.
又一次尝试化名
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.
我已经对其进行了搜索,大多数情况下都将这个问题作为两个模型都使用列表来回答。但是我不想使用列表,因为我正在使用 Django Rest Framework,所以我需要 QuerySet。所以我的问题是,如果我将列表用于联合,我可以将结果列表转换为 QuerySet。
注意:我不想在 Django 中使用 SQL 查询
还有其他方法可以完成这项任务吗?
【问题讨论】:
-
以上问题不返回查询集
-
from django.db.models import Q queryset = ABWrapper.objects.filter(Q(a__isnull=False)|Q(b__isnull=False)` 不起作用?
-
参加聚会很晚,但我遇到了这个问题,最后写了一个小包装。pypi.python.org/pypi/django-compoundqueryset
标签: django django-rest-framework