Django为字段设置手动算术公式 [英] Django set manual arithmetic formula for a field
问题描述
我想设置模型中字段的手动算术公式,该公式在模型的对象之间变化,并由某些用户设置,并根据外部模型名称进行设置。
I want to set manual arithmetic formula of a field in a model, the formula changes from object to object of the model and is set by some user and sets it depending on the foreign model name.
例如:
model B:
name =char
model A:
field 1 = int
field 2 = int
field 3 = foreign(model B)
field 4 = set formula
在模型A的对象1中,管理员将字段4 =字段1 +字段2设置为字段3 = x
In object 1 of model A, Admin sets field4 = field1 + field2 if field 3 = "x" from admin portal
在模型A的对象2中,如果
字段3 = y,则管理员从管理门户设置field4 = field1 * field2
In object 2 of model A, Admin sets field4 = field1 * field2 if field 3 = "y" from admin portal
在Django中可能吗?
Is this possible in Django?
实际上,我正在尝试将Excel工作表数据转换为Django应用程序给定选项卡的表(这里是模型A),我将有一些固定的列(这里是模型B),但是有一列,我将根据选项卡名称设置列的算术公式。
现在在我的Django应用程序中,基于模型A的名称,我需要能够为模型B设置公式。
Actually, I am trying to convert my excel sheet data into Django application, in my excel sheet for a given tab (here model A) I will have some fixed columns (here model B) but there is a column for which I will set the arithmetic formula of columns based on the tab name. Now in my Django application based on the name of model A, I need to be able to set a formula for model B.
什么是最好的方法
推荐答案
Django是否提供内置函数来实现此目的?
Does Django provide builtin functions to achieve this? No.
可以自定义Django来实现吗?是的。
Can you customize Django achieve this? Yes.
import operator
operator_map = {"+": operator.add, "-":operator.sub...}
class ModelB:
_operator <- while will store a raw operator
@property
def operator(self):
return operator_map[self._operator]
如果运算符将是动态的。 将运算符函数存储为另一列并存储在您的媒体资源中
If the operator is going to be dynamic. Store the operator function as another column and in your property
class Model
@property
def field4(self):
return self.field3.operator(self.field1, self.field2)
这篇关于Django为字段设置手动算术公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!