3

Suppose I had this following code:

 class MyModel(models.Model): ... ... def save(self, *args, **kwargs): # pre-save edits can go here... super(MyModel, self).save(*args, **kwargs) 

When I create and save a model, MyModel(blah, blah, blah), there is a possibility that one of the input fields is "None". In the overridden save method, the goal is to check for if a field is none, and if one is, change it to some other default value.

Are the input fields in args or kwargs? And is overriding save() even the proper way to do this?

I was thinking something like this:

 def save(self, *args, **kwargs): if 'username' in args and args['username'] is None: args['username'] = some_default_value super(MyModel, self).save(*args, **kwargs) 

So where are the input params? args* or **kwargs, thank you.

1 Answer 1

5

I think it's better a pre_save signal to see if a input value is None:

from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver class MyModel(models.Model): field1 = models.TextField() field2 = models.IntegerField() @receiver(pre_save, sender=MyModel) def mymodel_save_handler(sender, instance, *args, **kwargs): if instance.field1 is None or instance.field1 == "": instance.field1 = default_value 

If you prefer override save method you can access to the model fields with self

 def save(self, *args, **kwargs): if self.username is None: self.username = some_default_value super(MyModel, self).save(*args, **kwargs) 
Sign up to request clarification or add additional context in comments.

2 Comments

im getting a compile error, are u sure sender=MyModel isn't supposed to be sender='MyModel'?
Thanks, if anyone still can help, still a bit curious. Where can the instance fields be accessed when over-riding a save() method? Is it in args or kwargs?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.