2017-09-28 75 views
1

我想從我的表中的一些信息;總價格,總行程等兩個日期之間。這裏是我的查詢Django的ORM集團通過ID

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_tripsID ORDER BY NULL

到查詢結束。但我不想將它分組。

那麼,什麼是我做錯事?

Django的版本:(1,11,5, '最後',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' 
+0

你是什麼型號呢?你是如何管理它的?它是數據庫視圖? –

+0

我發現它,missusage,我必須使用聚合不標註。 https://stackoverflow.com/questions/7981837/difference-between-djangos-annotate-and-aggregate-methods – RockOnGom

+0

好,如果它幫助你,任何方式,您可以對您的問題添加答案,它可以幫助別人 –

回答

1

你只需要通過.order_by()加空順序 更多詳情default-ordering-or-order-by

+0

我已經嘗試過,但沒有工作。 – RockOnGom

+0

請添加您的模特,我嘗試一下 –

1

使用聚合不註釋,

每個對象摘要可以使用註釋()子句來生成。 當指定一個註釋()子句,則在查詢集 每個對象將具有指定值註釋。

聚集

我們需要的是在屬於此查詢集的對象 計算彙總值的方式。這是通過附加的集合() 條款到查詢集