0

我对 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() 之前?

4

1 回答 1

1

你不需要做任何事情来传递xyz变量——它是模型上的一个实例变量,所以它已经存在于model_instance传递给的变量中pre_save()

class MyField(models.TextField):

    def pre_save(self, model_instance, add):
        ...
        # Access model_instance.xyz here
        ...
        # Call the superclass in case it has work to do
        return super(MyField, self).pre_save(model_instance, add)
于 2012-10-03T20:16:10.007 回答