2013-06-05 24 views
1

我有一个自定义django字段子类来存储我自己的酸洗类。有什么办法,我可以设置一个model属性指向模型实例类从数据库中每个负载?Django泡菜字段加载其模型实例

到目前为止,我最好的猜测是在在unpickle过程中,to_python方法里面,但我不知道,如果Field有模型实例参考。

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

回答

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 
相关问题