如何在Django中计算字段上的不相关模型上加入两个查询集? Union
添加了更多行,但是,我正在考虑合并这些行以获取更多列,这是更经典的Join
作为一个不起作用的示例,如果我有两个模型定义为类似
class Temperature(models.Model):
timestamp=models.DateTimeField()
temperature=models.FloatField()
class WaterLevel(models.Model):
timestamp=models.DateTimeField()
data=models.JSONField()
我的数据库功能定义为
class Bucket(models.Transform):
template = "EXTRACT(EPOCH FROM %(expressions)s)::bigint/%(bucket_size)d"
allow_distinct = True
def __init__(self, expression, bucket_size=5,**extra):
if bucket_size<0:
raise ValueError('Bucket size must be a positive integer')
super().__init__(expression, bucket_size=int(bucket_size), **extra)
然后我有一个功能类似于
def get_buckets(bucket_size):
temperature_readings = (
Temperature.objects.values(bucket=Bucket("timestamp", bucket_size=15))
.annotate(temperatures=Count("bucket"))
.values("bucket", "temperatures")
)
water_levels = (
WaterLevel.objects.values(bucket=Bucket("timestamp", bucket_size=15))
.annotate(levels=Count("bucket"))
.values("bucket", "levels")
)
# This doesn't work, because there is no join method on a query_set
return temperature_readings.join(
water_levels, on=Q(tick=OuterRef("tick"))
).values_list("tick", "temperatures", "water_levels")
很显然,所使用的join
方法不存在,因此其签名已完全构建。我希望这会返回类似
[
( 1234, 10, 15),
( 1235, None, 15),
( 1236, 10, None),
( 1239, 1, 12),
...
]
Django是否内置任何方法来实现此目的?