0

In the following model, I am overriding its save method to use field's default value instead of null whenever null is encountered.

The method works, but is wordy. Is there a cleaner way of achieving the same?

class Activity(models.Model):
    date_added = models.DateTimeField(auto_now_add=True)
    number = models.IntegerField(default=0)
    athlete = models.ForeignKey(Athlete, on_delete=models.CASCADE, default=None)    
    start_date = models.DateTimeField(default=datetime.datetime.now)
    name = models.TextField(default="Unassigned")
    country = models.TextField(default="Unassigned")
    link = models.TextField(default="Unassigned")
    segment_efforts = models.TextField(default="Unassigned")
    distance = models.FloatField(null=True)
    average_speed = models.FloatField(null=True)

    def save(self, *args, **kwargs): 
        # overriding model's save method to use default field value instead of null, when null is encountered in JSON
        fields = self._meta.get_fields()
        for field in fields:
            field_value = getattr(self, field.name)
            if field_value == None:
                field_att = self.__class__._meta.get_field(field.name)
                default_value = field_att.get_default()
                field_value = setattr(self, field.name, default_value)

        return super(Activity, self).save(*args, **kwargs)

1 Answer 1

1

Actually, if you set null=False, when you create a new entry in your database, it will not store null values. If you also have a default value, then it should save the default value you have set.

The only problematic fields in your model that do not follow the above are distance and average_speed. Please consider setting a default value for them and not setting null to True.

With these changes, it is not necessary to override the save function.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but overriding the method is necessary: if you set model field to None and try to save, it will raise Not null constraint error, even with null=False and default set.
Have you tried not to set it to None? Just do not fill that field, then it should be saved with the default value.
Yes, in such case it will work. But my data is inconsistent and null will sometimes be encountered.
Then what I would do is an if-clause in Python so that if None, do not assign the field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.