Dmi*_*try 5 mysql django union django-models
我有两个 django 模型
class ModelA(models.Model):
title = models.CharField(..., db_column='title')
text_a = models.CharField(..., db_column='text_a')
other_column = models.CharField(/*...*/ db_column='other_column_a')
class ModelB(models.Model):
title = models.CharField(..., db_column='title')
text_a = models.CharField(..., db_column='text_b')
other_column = None
Run Code Online (Sandbox Code Playgroud)
然后我想使用合并该模型的两个查询集union
ModelA.objects.all().union(ModelB.objects.all())
Run Code Online (Sandbox Code Playgroud)
但在查询中我看到
(SELECT
`model_a`.`title`,
`model_a`.`text_a`,
`model_a`.`other_column`
FROM `model_a`)
UNION
(SELECT
`model_b`.`title`,
`model_b`.`text_b`
FROM `model_b`)
Run Code Online (Sandbox Code Playgroud)
当然我有例外The used SELECT statements have a different number of columns。
如何创建别名和假列以使用联合查询?
您可以对最后一列进行注释,以弥补列号不匹配的情况。
a = ModelA.objects.values_list('text_a', 'title', 'other_column')
b = ModelB.objects.values_list('text_a', 'title')
.annotate(other_column=Value("Placeholder", CharField()))
# for a list of tuples
a.union(b)
# or if you want list of dict
# (this has to be the values of the base query, in this case a)
a.union(b).values('text_a', 'title', 'other_column')
Run Code Online (Sandbox Code Playgroud)
在SQL查询中,我们可以用来NULL定义剩余的列/别名
(SELECT
`model_a`.`title`,
`model_a`.`text_a`,
`model_a`.`other_column`
FROM `model_a`)
UNION
(SELECT
`model_b`.`title`,
`model_b`.`text_b`,
NULL
FROM `model_b`)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4355 次 |
| 最近记录: |