我在为 Django 应用程序建模时遇到了意想不到的困难。我有一个由属性组成的模型。某些属性具有外部(主数据)表示。我希望能够获取我在应用程序中使用的表示形式以及主数据表示形式。我的想法是使用自定义 django.db.models 字段,并添加一个方法来获取主数据表示。然后我可以使用 model.field
作为“ native ”表示,使用 model.field.mdm_guid()
作为外部表示。
但是,当继承Field
时,我还没有找到访问该字段自身值的方法。
目前,代码如下所示:
class MdmField(TextField):
def __init__(self, *kargs, **kwargs):
self.mdm_type = kwargs.pop('mdm_type', None)
def mdm_guid(self, value):
return masterdata[self.mdm_type].get(value, 0)
masterdata
字典包含这些外部表示,但这对于这个问题并不重要。
我对需要传递字段值感到困扰!我不能从字段本身访问字段的值吗?有没有办法从现场获取模型?
谢谢!
最佳答案
请注意 documentation 的这一部分:
It’s important to realize that a Django field class is not what is stored in your model attributes. The model attributes contain normal Python objects. The field classes you define in a model are actually stored in the
Meta
class when the model class is created (the precise details of how this is done are unimportant here). This is because the field classes aren’t necessary when you’re just creating and modifying attributes. Instead, they provide the machinery for converting between the attribute value and what is stored in the database or sent to the serializer.
这就是为什么自定义字段要求您传入一个值 - 它只是进行转换,而不是模型实例的一部分。
相反,您可以定义一个具有 mdm_guid()
方法的普通旧 Python 类,并让您的自定义字段获取并返回该方法。有关示例,请参阅上面引用的文档中的 Hand
类和 HandField
类之间的区别。
关于python - 从字段内获取 Django 字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33480187/