gpt4 book ai didi

python - Django ORM 按 ID 分组

转载 作者:行者123 更新时间:2023-11-29 05:59:11 26 4
gpt4 key购买 nike

我正在尝试从我的表中获取一些信息;两个日期之间的总价、总行程等。这是我的查询

start_date = Utils.subtract_day(datetime.datetime.today(), 30)
end_date = datetime.datetime.today()
trips = TbPastTrips.objects.filter(identity=identity, creation_time__range=(start_date, end_date),
status=TripStatus.PAYMENT_COMPLETED)\
.annotate(total_price__=Sum('price'), total_tip=Sum('tip_amount'),
total_additional_fees=Sum('additional_fees'), total_trip=Count('price')) \
.values('total_price__', 'total_tip', 'total_additional_fees', 'total_trip')

print(trips.query)

这是我期望从上面的查询集中得到的原始 sql 查询:

SELECT SUM(`tb_past_trips`.`PRICE`) AS `total_price__`, SUM(`tb_past_trips`.`TIP_AMOUNT`) AS `total_tip`, SUM(`tb_past_trips`.`ADDITIONAL_FEES`) AS `total_additional_fees`, COUNT(`tb_past_trips`.`PRICE`) AS `total_trip` FROM `tb_past_trips` WHERE (`tb_past_trips`.`IDENTITY` = 44444444444 AND `tb_past_trips`.`CREATION_TIME` BETWEEN '2017-08-29 10:36:19.446371' AND '2017-09-28 10:36:19.446405' AND `tb_past_trips`.`STATUS` = 4)

但它在下面添加了额外的查询:

GROUP BY tb_past_trips.ID ORDER BY NULL

查询结束。但我不想对它进行分组。

那么我做错了什么?

Django 版本 :(1, 11, 5, 'final', 0)

python 3.6.2

添加模型:

class TbPastTrips(models.Model):
id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase.
transaction_id = models.CharField(db_column='TRANSACTION_ID', max_length=50, blank=True, null=True) # Field name made lowercase.
identity = models.CharField(db_column='TAXI', max_length=20) # Field name made lowercase.
price = models.IntegerField(db_column='PRICE', blank=True, null=True) # Field name made lowercase.
tip_amount = models.IntegerField(db_column='TIP_AMOUNT', blank=True, null=True) # Field name made lowercase.
additional_fees = models.IntegerField(db_column='ADDITIONAL_FEES', blank=True, null=True) # Field name made lowercase.
total_price = models.IntegerField(db_column='TOTAL_PRICE', blank=True, null=True) # Field name made lowercase.
creation_time = models.DateTimeField(db_column='CREATION_TIME') # Field name made lowercase.

class Meta:
managed = False
db_table = 'tb_past_trips'

最佳答案

使用聚合而不是注释,

Per-object summaries can be generated using the annotate() clause. When an annotate() clause is specified, each object in the QuerySet will be annotated with the specified values.

聚合

What we need is a way to calculate summary values over the objects that belong to this QuerySet. This is done by appending an aggregate() clause onto the QuerySet

关于python - Django ORM 按 ID 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46467296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com