0

I'm trying to build a filter depending on if an object attribute is empty or not.

Below my 2 class tables:

Buy model
id   buy_price sell_price
10   15        50
20   30        110
30   80        250

Sell model
item buyer*
10   Ana

*This is an OneToOneField(Buy)

What I really need is to query a sum of the buy_price and sell_price that are NOT listed in Sell model (my_buy_object.sell.buyer == '')

I tryied the code below but it's not working properly:

buys = Buy.objects.order_by('-id')
sum_price = [buy.buy_price for buy in buys if buy.sell.buyer == '']
sum_price = sum(sum_price)

The correct answer for this code should be sum_buy_price: 110 and sum_sell_price: 360

Thank you!

EDIT: added the models:

class Buy(models.Model):
   category = models.ForeignKey(Category, on_delete=models.CASCADE)
   image = models.FileField()
   date = models.DateField(default=timezone.now)
   buy_price = models.DecimalField(max_digits=6, decimal_places=2)
   sell_price = models.DecimalField(max_digits=6, decimal_places=2)

   def __str__(self):
       return f'{self.id}'

class Sell(models.Model):
   item = models.OneToOneField(Buy, related_name='sell', 
   on_delete=models.CASCADE)
   date = models.DateField(default=timezone.now)
   discount = models.DecimalField(max_digits=6, decimal_places=2)
   total_paid = models.DecimalField(max_digits=6, decimal_places=2)
   buyer = models.ForeignKey(Buyer, related_name='sell', 
   on_delete=models.CASCADE)

   def __str__(self):
       return f'{self.buyer}'
2
  • can you add your models here ? Commented May 14, 2020 at 1:43
  • Done, I've just added the models! Commented May 14, 2020 at 2:06

1 Answer 1

1

To filter empty related fields, use isnull filter

from django.db.models import Sum

Buy.objects.filter(sell__buyer__isnull=True
                   ).aggregate(sum_buy_price=Sum('buy_price'),
                               sum_sell_price=Sum('sell_price'))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! It was exactly what I was expecting!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.