Django:在运行时将参数传递给ModelField

时间:2012-10-03 13:37:24

标签: django django-models

我是Python + Django的新手,我遇到了以下问题。我创建了一个自定义的ModelField,如:

class MyField(models.TextField):

    def __init__(self, *args, **kwargs):
        super(MyField, self).__init__(*args, **kwargs)

    def pre_save(self, model_instance, add):
        # custom operations here
        # need access to variable xyz

使用此字段的模型类似于:

 class MyModel(models.Model):
     my_field = MyField()

     def __init__(self, model, xyz, *args, **kwargs):
         self.instance = model
         # how to pass xyz to ModelField before pre_save gets called?
         self.xyz = xyz 

     def save(self, *args, **kwargs):
         if self.instance:
             self.my_field = self.instance    

问:就像在评论中所说的那样,有没有办法在运行时将变量传递给ModelField实例,理想情况是在调用my_field.pre_save()之前?

1 个答案:

答案 0 :(得分:1)

您无需执行任何操作即可传递xyz变量 - 它是模型上的实例变量,因此它已存在于传递给{的model_instance变量中{1}}

pre_save()