python - 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,我想要用户在第二个字段中输入一个值后,从第一个字段中减去它,第一个更改为旧结果的结果减去用户在第二次输入的值
解决方案
您可以让来自模型的数据直接在 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 '-'
推荐阅读
- javascript - 如何找到执行 eval 代码的 [content] 脚本
- r - R:如何根据 R 中另一行的值扩展一行中的值?
- html - 当html代码不直接包含选项时如何使一个按钮默认单选按钮
- axapta - Microsoft Dynamics ax 2012 如何从 2 个不同的表创建自动查找
- azure-devops - 在 Azure DevOps 中为不同环境提供不同测试用例集的最佳实践
- google-sheets - 谷歌电子表格条件格式 - 如果值高于则突出显示单元格
- jquery - 使用 jQuery 数组添加动态类名
- image-processing - 自适应傅里叶滤波器
- css - 角度/引导轮播中的图像不居中
- apache-nifi - NiFi:带有 QueryDatabaseTableRecord 组件的问题