SHARE
TWEET

define quantity for each selected item in the same time

a guest Jul 22nd, 2019 79 in 338 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Product(models.Model):
  2. name = models.CharField(max_length=50)
  3. price = models.PositiveIntegerField(default=1)
  4.  
  5. def __str__(self):
  6.     return self.name
  7.  
  8.  
  9. class Order(models.Model):
  10. id = models.AutoField(primary_key = True)
  11. products = models.ManyToManyField(Product ,through='ProductOrder')
  12.  
  13. @property
  14. def total(self):
  15.     return self.productorder_set.aggregate(
  16.         price_sum=Sum(F('quantity') * F('product__price'),
  17. output_field=IntegerField()) )['price_sum']
  18.  
  19.  
  20.  
  21. class ProductOrder(models.Model):
  22.  
  23.  
  24. product = models.ForeignKey(Product, on_delete=models.CASCADE ,
  25. null=True,blank=True)
  26. ordering = models.ForeignKey(Order, on_delete=models.CASCADE ,  
  27. blank=True)
  28. quantity = models.IntegerField(default=1)
  29.  
  30. #to make a new instance from order,but doesnt make! before saving
  31. ProductOrder
  32. def create_order(sender, instance, **kwargs):
  33.  
  34. instance.ordering.save()
  35.  
  36.  
  37. pre_save.connect(create_order,sender=ProductOrder)
  38. forms.py
  39.  
  40. class ProductOrdering(forms.ModelForm):
  41. class Meta:
  42.     model = ProductOrder
  43.     fields = ['product','ordering','quantity']
  44. views.py
  45.  
  46. class ProductOrderCreate(CreateView):
  47. form_class = ProductOrdering
  48. model = ProductOrder
  49. template_name = 'create_product_order.html'
  50. success_url = '/orders/'
  51. def form_valid(self,form):
  52.     form.instance.ordering = Order.objects.order_by('-pk')[0]
  53.  
  54.     return super(ProductOrderCreate,self).form_valid(form)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top