Home > Back-end >  Django formset save() writes new object on database?
Django formset save() writes new object on database?

Time:01-10

So I have MyModel:

class MyModel(models.Model):
    name = models.CharField(_('Name'), max_length=80, unique=True)
    ...

    def save(self, *args, **kwargs):
        if MyModel.objects.count() >= 5:
            raise ValidationError("Can not have more than 5 MyModels!")
        super().save(*args, **kwargs)  # Call the "real" save() method.

There are already 5 objects from MyModel on the database. I have a page where I can edit them all at the same time with a formset. When I change one or more of them, I will get the Validation Error "Can not have more than 5 MyModels!". Why is this happenning? I tought the formset was supposed to edit the existing objects, but it appears to be writing a new one and deleting the old one.

What is really happening when I do a formset.save() on the database? Do I have to remove the save() method?

CodePudding user response:

The save method inside the Model is called regardless you are creating or editing. Although you can distinguish between them by checking if the object has a primary key, like this:

if not self.pk and MyModel.objects.count() >= 5:

If you want more sophisticated control over validation, I suggest putting them in the forms. Specially if you want to limit the number of formset, you can check this documentation.

  • Related