Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change input fields while overriding a django save() method

Tags:

python

django

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.

like image 858
Lucas Ou-Yang Avatar asked May 15 '26 04:05

Lucas Ou-Yang


1 Answers

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)
like image 73
Victor Castillo Torres Avatar answered May 17 '26 19:05

Victor Castillo Torres