tags:

views:

27

answers:

2

For my project I need to count distinct products that have a balance larger than $100.
The model kinda looks like this:

class Client(models.Model):
  ...

class Product(models.Model):
  ...

class ClientProduct(models.Model):
  client = models.ForeignKey(Client)
  product = models.ForeignKey(Product)

class Balance(models.Model):
  clientproduct = models.ForeignKey(ClientProduct)
  balance = models.DecimalField(max_digits=10, decimal_places=2)

but I'm clueless... And other related questions here in SO don't really address this scenario...
Please help.

+1  A: 

It sounds like you are looking to sum all Balances grouped by ClientProduct.product, and filter products who have a balance sum greater than $100. Something like:

from django.db.models import Sum
Product.objects.annotate(
              balance_sum=Sum('clientproduct__balance')
         ).filter(balance_sum__gte=100)
Daniel Roseman
not exactly what I was looking for, but I learned something nonetheless. Thanks for the reply
EroSan
+1  A: 

Seems like something like this should work:

balances_over_100 = Products.objects.filter(clientproduct__balance__gte=100)
balances_over_100.count()
godswearhats
I had no idea you could filter using the classes for which the class serve as foreign key! Thanks.btw, this works too and it saves one line Products.objects.filter(clientprodduct__balance__balance__gt=100).count()
EroSan
Yep, I was being more explicit to help out ... glad this fixed your issue!
godswearhats