Django Pickle Field在加载时访问其模型实例

时间:2013-06-05 15:31:48

标签: python django pickle

我有一个自定义的django字段子类,用于存储我自己的pickle类。在数据库的每次加载中,我是否可以设置model属性指向 pickle 类上的模型实例

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

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

1 个答案:

答案 0 :(得分: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