mzu
mzu

Reputation: 759

Django: Passing arguments to ModelField at runtime

I am fairly new to Python + Django and I am stuck with the following problem. I have created a custom ModelField like:

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

The model using this field looks something like:

 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    

Q: Like it says in the comment, is there a way to pass a variable to the ModelField instance at runtime, ideally before my_field.pre_save() gets called?

Upvotes: 0

Views: 92

Answers (1)

Ian Clelland
Ian Clelland

Reputation: 44132

You don't need to do anything to pass the xyz variable on -- it is an instance variable on the model, so it is already present in the model_instance variable that gets passed to 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)

Upvotes: 1

Related Questions