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