2012-10-03 41 views
0

我對Python + Django相當陌生,並且遇到以下問題。我創建了一個自定義的ModelField喜歡: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

爲什麼model_instance變量你不在MyModel的__init__中傳遞它嗎? –

+0

什麼時候,你想要這個被叫? 「pre_save之前」的描述不夠充分。 –

+0

@ParitoshSingh:這正是我正在做的。 xyz被傳遞到MyModel的init()中,並且從這裏我想傳遞它,以便我可以在ModelField的pre_save()方法中使用它。有任何想法嗎? – mzu

回答

1

你不需要做任何事情來轉嫁xyz變量 - 這是對模型的實例變量,所以它已經存在於被傳遞給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) 
+0

doh。謝謝。 – mzu