基于这个答案
我有这个模型
class PortfolioExchangeTransaction(models.Model):
creator = models.ForeignKey('accounts.Account', on_delete=models.SET_NULL, null=True, blank=True,
verbose_name=_('Creator'))
create_time = models.DateTimeField(default=timezone.now, verbose_name=_('Create Time'))
portfolio = models.ForeignKey(Portfolio, on_delete=models.SET_NULL, null=True, blank=True,
verbose_name=_('Portfolio'), related_name='exchange_transaction')
type = models.CharField(max_length=40, choices=Transaction_TYPE, blank=True, null=True, verbose_name=_('Type'))
exchange = models.ForeignKey(BorseExchange, on_delete=models.SET_NULL, null=True, blank=True,
verbose_name=_('Exchange'))
count = models.IntegerField(default=0, verbose_name=_('Count'))
我想对每个交易所的所有PortfolioExchangeTransaction的计数求和
所以我想要sum相似的记录queryset每次交换如下代码:
result = PortfolioExchangeTransaction.objects.all().values('exchange')
,我希望得到这样的东西:
<QuerySet [{'exchageid': 591}, {'exchageid': 512}, {'exchageid': 248}, {'exchageid': 940}]>
但是值是这样的:
<QuerySet [{'exchageid': 591}, {'exchageid': 591}, {'exchageid': 512}, {'exchageid': 248}, {'exchageid': 591}, {'exchageid': 591}, {'exchageid': 591}, {'exchageid': 591}, {'exchageid': 940}, {'exchageid': 591}, {'exchageid': 248}, {'exchageid': 248}]>
<标题>更新
result.annotate(sum_count=Sum('count', output_field=BigIntegerField()))
所以我不能用distinct因为给了这个:
NotImplementedError('annotate() + distinct(fields) is not implemented.')
如何解决这个问题?
标题>您可以在这里使用distinct()
:
PortfolioExchangeTransaction.objects.all().values('exchange').distinct()
更新此处使用GROUP BY
:
result = PortfolioExchangeTransaction.objects.values('exchange').annotate(sum=Sum('count')).values('exchange', 'sum')