Django-如何在基于功能的视图中使用model方法
我创建了一个函数,可以对模型中的所有金额求和 我如何在基于函数的视图(FBV)中执行此函数(get_tot_order_price) def myview(请求):Django-如何在基于功能的视图中使用model方法,django,Django,我创建了一个函数,可以对模型中的所有金额求和 我如何在基于函数的视图(FBV)中执行此函数(get_tot_order_price) def myview(请求): 因此,get\u tot\u order\u price是一种实例方法。这意味着您需要一个BillingItemmodel的实例来执行此功能。在FBV中,您可以获取一个实例,然后执行此方法 def myview(请求): obj=BillingItem.objects.get(id=some\u id) 总价=订单总价() 这将
因此,
get\u tot\u order\u price
是一种实例方法。这意味着您需要一个BillingItem
model的实例来执行此功能。在FBV中,您可以获取一个实例,然后执行此方法
def myview(请求):
obj=BillingItem.objects.get(id=some\u id)
总价=订单总价()
这将给出给定实例的
BillingItem
模型的总价。self.order\u price
是一个浮动字段,为什么要使用self.order\u price.all()
?您的获取订单价格肯定会出错。哦,对不起。我只是修改了代码,结果出错了。我又修好了。
class Cart(TimeStampedModel, models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
paid = models.BooleanField(default=False)
def get_price(self):
return self.product.price * self.quantity
class BillingItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.PROTECT)
products = models.ManyToManyField(Cart)
quantity = models.PositiveIntegerField()
def __str__(self):
return '{}'.format(self.id)
def get_tot_order_price(self):
total = 0
for price in self.products.all():
total += price.get_price()
return total