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