【问题标题】:How to create Union in Django queryset如何在 Django 查询集中创建联合
【发布时间】: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 查询

还有其他方法可以完成这项任务吗?

【问题讨论】:

标签: django django-rest-framework


【解决方案1】:

您可以在 django 中使用 Q 对象进行复杂的过滤。查看this_link 了解实现细节。

【讨论】:

    猜你喜欢
    • 2019-12-04
    • 1970-01-01
    • 2021-11-10
    • 2023-03-27
    • 2021-09-03
    • 2014-11-11
    • 2013-04-18
    • 2022-11-08
    • 2011-05-23
    相关资源
    最近更新 更多