Python Django:使用对象属性筛选查询

Python Django:使用对象属性筛选查询,python,django,Python,Django,我试图根据对象属性是否为空来构建过滤器 下面是我的两张班级表格: 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) 我真正需要的是查询未在销售模型my_buy_object.sell.buyer== 我尝试了下面的代码,但无法正常工作

我试图根据对象属性是否为空来构建过滤器

下面是我的两张班级表格:

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)
我真正需要的是查询未在销售模型my_buy_object.sell.buyer==

我尝试了下面的代码,但无法正常工作:

buys = Buy.objects.order_by('-id')
sum_price = [buy.buy_price for buy in buys if buy.sell.buyer == '']
sum_price = sum(sum_price)
此代码的正确答案应该是sum\u buy\u price:110和sum\u sell\u price:360

谢谢大家!

编辑:添加模型:

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

要筛选空的相关字段,请使用筛选器


你能在这里添加你的模型吗?完成了,我刚刚添加了模型!非常感谢你!这正是我所期待的!
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'))