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
413 views
in Technique[技术] by (71.8m points)

how sum ForeignKey to ManyToManyField django queryset

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

and want to sum count and portfolio of this model based on exchange

so i use below code :

transes.annotate(exc_count=Case(
            When(type='negative', then=F('count') * -1),
            When(type='positive', then=F('count')),
        )
        ).values('exchange').annotate(
            sum_count=Sum('exc_count')
        ).values('exchange', 'sum_count').annotate(
            portfolios=Value(None, output_field=ManyToManyField(Portfolio))
        )

the result is :

<QuerySet [{'exchange': 248, 'sum_count': 4000, 'portfolios': None}, {'exchange': 512, 'sum_count': 10000, 'portfolios': None}, {'exchange': 591, 'sum_count': 0, 'portfolios': None}, {'exchange': 940, 'sum_count': 10000, 'portfolios': None}]>

as can see i create portfolio field and want to sum foreignkeys to manytomanyfield ( now is None value )

how can do that?

question from:https://stackoverflow.com/questions/65902868/how-sum-foreignkey-to-manytomanyfield-django-queryset

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

1 Answer

0 votes
by (71.8m points)

We can annotate on instance fields not the object instances.

As quoted by Todor: Annotation is a computation that is done on a database level. Django provides you only a set of basic computations which can be processed by the database - SUM, AVERAGE, MIN, MAX and so on...

Conclusion: We can't convert all ForeignKey instances to ManyToManyField.


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

2.1m questions

2.1m answers

60 comments

57.0k users

...