django - get total price for the products in m2m field in save -


django 1.8 i'm trying total price products in m2m field.

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) 

when try save order object, code above produce valueerror:

"<order: none>" needs have value field "order" before   many-to-many relationship can used. 

do have specific requirements save total in database? if not,

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

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -