我有一个查询,该查询根据我的amount
的{{1}}字段来计算运行余额,并按Transaction
进行排序。当created_time
和date
是同一天时,这对于获得准确的运行平衡非常有用。但是,created_time
并不总是与交易的date
相匹配。我有什么办法可以使用created_time
来进行此余额的计算?
当前查询:
date
完整用法:
queryset = self.queryset.annotate(balance=Window(Sum('amount'), order_by=F('created_time').asc())).all().order_by('-created_time')
型号:
class TransactionViewSet(viewsets.ModelViewSet):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
def list(self, request, *args, **kwargs):
queryset = self.queryset.annotate(balance=Window(Sum('amount'), order_by=F('created_time').asc())).all().order_by('-created_time') # noqa: E501
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
序列化器:
class Transaction(models.Model):
date = models.DateField()
payee = models.CharField(max_length=256)
category = models.CharField(max_length=256)
amount = MoneyField(max_digits=19,
decimal_places=2,
default_currency='USD')
memo = models.CharField(max_length=256)
is_cleared = models.BooleanField()
paid_or_deposited = models.BooleanField()
created_time = models.DateTimeField(db_index=True, # maybe remove the index
auto_now_add=True)
modified_time = models.DateTimeField(auto_now=True)
如果我尝试在class TransactionSerializer(serializers.ModelSerializer):
balance = serializers.DecimalField(
decimal_places=2, max_digits=19, read_only=True)
class Meta:
"""Meta class to map serializer's fields with the model fields."""
model = Transaction
fields = ('id', 'date', 'payee', 'category',
'amount', 'balance', 'created_time', 'modified_time', 'is_cleared', 'paid_or_deposited')
函数中使用date
,则计算出的余额不正确。我相信这是因为Window
是一个非唯一字段,但是我不确定。
当前查询的问题是我可能会在2018年12月25日输入date
为12/20/2018的事务。结果是此新交易返回与其他12/25/2018交易一起排序的地方,我希望将其与12/20/2018交易一起排序。希望这是有道理的。