首页 > 解决方案 > Django 从另一个表中的另一个字段中减去一个字段并保存结果

问题描述

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)

我有两个模型,第一个有一个 int 字段,第二个是一个 int,我想要用户在第二个字段中输入一个值后,从第一个字段中减去它,第一个更改为旧结果的结果减去用户在第二次输入的值

标签: pythondjangodjango-models

解决方案


您可以让来自模型的数据直接在 views.py 文件中相互交互。

例如,您可以:

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

您还可以将属性添加到您的其中一个在内部进行此数学运算的模型中。

示例模型.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 '-'

推荐阅读