python - 从字段内获取 Django 字段值

标签 python django django-models

我在为 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/

相关文章:

python - 相同的按钮,不同的文本。 Selenium python

python - 为什么我在从不同进程读取文件时出现竞争条件?

Django:__in 查询查找不维护查询集中的顺序

django - 在 Django Admin 中向每个 View (base_site.html)添加内容

python - 在 Django 中,我有一个复杂的查询,我只需要通过外键获取唯一值,这可能吗?

python - 如何使用 Pandas Profiling 包仅生成相关性和散点图?

python - 基于日期时间索引和列的 Pandas 回填值

Javascript 模板不运行以 '}' 开头的 : SyntaxError: unexpected garbage after function body,

Django:如何使用中间件将请求重新路由到不同的 View

python - 编写管理器来过滤查询集结果