我有一个自定义的django字段子类,用于存储我自己的pickle类。在数据库的每次加载中,我是否可以设置model
属性指向 pickle 类上的模型实例?
到目前为止,我最好的猜测是在to_python
方法内的unpickling过程中,但我不确定Field
是否有对模型实例的引用或 class 。
编辑1: to_python
方法内部的模型引用确实是对类的引用,而不是实例
答案 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