Django 1.8我试图在m2m领域获得产品的总价。
from django.models.db import Sum
class Product(models.Model):
...
price = models.DecimalField(default=0, max_digits=9, decimal_places=2)
class Order(models.Model):
...
products = models.ManyToManyField(Product, related_name='orders')
total = models.DecimalField()
...
def save(self, *args, **kwargs):
self.total = self.products.all().annotate(Sum('price'))
super(Order, self).save(*args, **kwargs)
当我尝试保存Order对象时,上面的代码会产生ValueError:
"<Order: None>" needs to have a value for field "order" before this
many-to-many relationship can be used.
答案 0 :(得分:0)
您是否有特定要求将此总数保存在数据库中?如果没有,
class Order(models.Model):
...
products = models.ManyToManyField(Product, related_name='orders')
...
@property
def total(self):
result = self.products.aggregate(Sum('price'))
return result['price__sum']
答案 1 :(得分:0)
最佳方式,信号:
https://docs.djangoproject.com/en/1.8/ref/signals/#m2m-changed
这是一个例子:
@receiver(m2m_changed, sender=BusquedaInmueble.zonas.through)
def post_save_busqueda_m2m (sender, action, instance, *args, **kwargs):
busqueda = instance
if action == 'post_add':