from django.db import models
class Product(models.Model):
name = models.CharField(max_length = 50)
quantity = models.FloatField(default=0)
def __str__(self):
return self.name
class Customer(models.Model):
name = models.CharField(max_length=100)
primary_contact = models.CharField(max_length=10)
secondary_contact = models.CharField(max_length=10)
address = models.TextField(blank=True)
def __str__(self):
return self.name
class Issue(models.Model):
date = models.DateTimeField(auto_now_add = True)
customer = models.ForeignKey(Customer, on_delete = models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE, )
quantity = models.PositiveIntegerField()
kt = models.IntegerField()
rate = models.FloatField()
vat = models.IntegerField(default=15)
@property
def kt_21(self):
return self.kt / 21 * self.quantity
@property
def vat_amt(self):
return self.quantity * self.rate * self.vat/100
@property
def total_amt(self):
return self.quantity * self.rate + self.vat_amt
def __str__(self):
return str(self.customer) + " - "+ str(self.total_amt)+' SAR'
I have these models now I what I want is that when I issue a product and enter some quantity in the Issue model the same amount of quantity should be deducted from the Product model's quantity field.
you can simply make an update query after saving your IssueForm. Like this:
def submit_issue(request):
if request.method == "POST":
form = IssueForm(request.POST)
if form.is_valid():
form_product_qty = form.cleaned_data["quantity"]
product_id = form.cleaned_data["product_id "]
user = form.save()
product = Product.objects.get(id=product_id)
product.quantity = product.quantity - form_product_qty
product.save()