我需要将许多 acct_id 的记录合并到按“月”字段分组的单个摘要中。所有其他数据(例如“value”和“cash_in”)都需要进行 Sum()

class Cashflow ( models.Model ):
   acct_id = models.ForeignKey ( Acct )
   month = models.DateField ( auto_now = False, auto_now_add = False, null = False, blank = True )
   value = models.IntegerField ( blank = True, default = 0 )
   cash_in = models.IntegerField ( blank = True, default = 0 )
   cash_out = models.IntegerField ( blank = True, default = 0 )
   transfer = models.IntegerField ( default = 0 )

我很难将所有数据分组。

还希望月份井然有序。


不确定这是最好的方法,但它似乎有效。

任何有关改进的建议将不胜感激。干杯。

qs = Cashflow.objects.all () 
    .filter ( acct_id = id ) 
    .annotate ( m = TruncDate ( 'month' ) ) 
    .order_by ( 'm' ) 
    .values ( 'm' ) 
    .annotate ( **{ 'value': Sum ( 'value' ) } ) 
    .annotate ( **{ 'cash_in': Sum ( 'cash_in' ) } ) 
    .annotate ( **{ 'cash_out': Sum ( 'cash_out' ) } ) 
    .annotate ( **{ 'transfer': Sum ( 'transfer' ) } )