Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

orm - django queryset values not merging

based on this answer

i have this model

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'))

i want to sum count of all PortfolioExchangeTransaction per exchange

so i want sum similar records queryset per exchange as below code:

result = PortfolioExchangeTransaction.objects.all().values('exchange')

and i was hopping get something like this:

<QuerySet [{'exchageid': 591}, {'exchageid': 512}, {'exchageid': 248}, {'exchageid': 940}]>

but with values i got like this:

<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}]>

Updated

i want use annotate after abow:

result.annotate(sum_count=Sum('count', output_field=BigIntegerField()))

so i can't use distinct because giving this :

NotImplementedError('annotate() + distinct(fields) is not implemented.')

how fix this?

question from:https://stackoverflow.com/questions/65897663/django-queryset-values-not-merging

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use distinct() here:

PortfolioExchangeTransaction.objects.all().values('exchange').distinct()

Update

Use GROUP BY here:

result = PortfolioExchangeTransaction.objects.values('exchange').annotate(sum=Sum('count')).values('exchange', 'sum')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...