Filter by sum of filtered related objects?

21 views
Skip to first unread message

Dustin Wyatt

unread,
Jan 3, 2019, 12:32:55 PM1/3/19
to Django users
Given the following models:


class Transaction(models.Model):
  amount = models.IntegerField()
  date = models.DateField()
  terms = models.ForeignKey('Terms')


class Terms(models.Model):
  name = models.CharField(max_length=100)
  timezone = models.CharField(max_length=50)


I need to annotate Terms with the sum of the related Transaction.amount's where the Transaction.date is between two dates and what those two dates are varies by Terms.timezone.

Possible?

Todor Velichkov

unread,
Jan 4, 2019, 2:51:54 PM1/4/19
to Django users
Maybe something like this should work:

Terms.objects.annotate(
    transactions_sum
=models.Subquery(
       
Transaction.objects.filter(
            terms
=models.OuterRef("pk"),
       
)
       
# Now In order to filter by some date_range
       
# which vary by timezone, you would want to
       
# annotate the date field with the applied timezone
       
# something like
       
# .annotate(tz_date=Func('date', Value('GMT'), models.OuterRef("timezone"), function='CONVERT_TZ'))
       
# .filter(tz_date__range=(min_date, max_date))
       
.values('terms')
       
.annotate(amount_sum=models.Sum("amount"))
       
.values('amount_sum'),
        output_field
=models.IntegerField(),
   
)
)

Aakash Choudhary

unread,
Jan 4, 2019, 2:55:42 PM1/4/19
to django...@googlegroups.com
Yes it is possible 

Lent Asia technologies pvt Ltd,

Aakash chaudhary

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/02257cdb-55a5-4ae9-bc2d-3b3fef0ef91f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages