abdallah omar ahmed
abdallah omar ahmed

Reputation: 3

Django Subtract a field from another field in another table and save the result

class prodect(models.Model):
      name = models.CharField(max_length=50)
      cwan = models.DecimalField(max_digits=5, decimal_places=2)
class orders(models.Model):
      names = models.CharField(max_length=50)
      prodects = models.ForeignKey(prodect,on_delete=models.CASCADE)
      count = models.DecimalField(max_digits=7, decimal_places=2)

I have two models the first have a int field and The second is a int and I Want After the user enters a value in the second field, it is subtracted from the first, and the result of the first changes to its old result minus the value that the user entered in the second

Upvotes: 0

Views: 740

Answers (1)

Shyrtle
Shyrtle

Reputation: 647

You can have data from the models interact with each other directly in the views.py file.

For example, you could have:

from .models import prodect, orders
def example(request):
    prodect = prodect.objects.all()
    orders = orders.objects.all()
    foo = prodect.cwan - orders.count
    return foo

You could also add a property to one of your models that is doing this math internally.

Example models.py

class prodect(models.Model):
    name = models.CharField(max_length=50)
    cwan = models.DecimalField(max_digits=5, decimal_places=2)
class orders(models.Model):
    names = models.CharField(max_length=50)
    prodects = models.ForeignKey(prodect,on_delete=models.CASCADE)
    count = models.DecimalField(max_digits=7, decimal_places=2)

    @property
    def math(self):
        if self.count:
            x = self.count - self.prodects.cwan
            return x
        else:
            return '-'

Upvotes: 2

Related Questions