1

我有一个自定义 django 字段子类,用于存储我自己的腌制类。有什么方法可以在每次从数据库加载时设置一个model指向我的腌制类上的模型实例的属性?

到目前为止,我最好的猜测是在方法内部的 unpickling 过程中to_python,但我不确定 是否Field有对模型实例的引用。

编辑1:方法内部的模型引用to_python确实是对的引用,而不是实例

4

1 回答 1

0

弄清楚了!

我像这样覆盖了模型的__init__方法:

class MyModel(models.Model):
    def __init__(self, *args, **kwargs):
        # Don't do any extra looping or anything in here because this gets called
        # at least once for every row in each query of this table
        self._meta.fields[2].model_instance = self
        super(MyModel, self).__init__(*args, **kwargs)
    field1 = models.TextField()
    field2 = models.PickleField()
    field3 = models.DateTimeField()

然后在我的字段子类中:

def to_python(self, value):
    # logic and unpickling, then right before your return:
    if hasattr(self, 'model_instance'): # avoid AttributeError if list, dict, etc.
        value.model_instance = self.model_instance
    return value
于 2013-06-05T18:32:35.190 回答