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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…