模型实例方法

时间:2020-09-17 23:09:02

标签: django-models

这是我的两个模型:

class Bill(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
professional = models.ForeignKey(Professional, on_delete=models.CASCADE)
date = models.DateField(default=timezone.now, blank=True)
bill_status = models.BooleanField(initial=True)
close_date = models.DateField(blank=True, Null=True)
def __str__(self):
    return str(self.date) + " " +self.client.first_name +" " +self.client.last_name
class Meta:
    ordering = ['-date']

class BillableItem(models.Model):
bill = models.ForeignKey(Facture, on_delete=models.CASCADE)
date = models.DateTimeField(default=timezone.now, blank=True)
service = models.ForeignKey(Service, on_delete=models.CASCADE)
qty = models.FloatField()
price = models.SmallIntegerField()

我想要这样的东西

Bill.objects.filter(BillableItem__bill.aggregate(sub_total= Sum(F('qty') * F('price'), output_field=FloatField()))
      

但是作为模型实例方法,这样我就不必每次都重写它。我对Django不太熟悉。

这是原始(My)SQL的样子

select 
      sum(price*qty) 
from 
     Bill_Billable as a
left join 
     Bill_Bill as b on b.id = a.bill_id
where 
     b.id=1 <-That would change based on the instance

谢谢

0 个答案:

没有答案
相关问题