我需要将许多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 )
我很难将所有数据分组。
也希望这几个月有序。
答案 0 :(得分: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' ) } )