Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to find in forms .save() method if Model Form is creating a new record or updating existing one?

What I am doing to know if the form is creating a new record or updating existing one is

class MyForm(forms.ModelForm):
    def save(self, commit=True):
        _new = True if not self.instance.id else False
        keyword = super(MyForm, self).save()
        if _new:
            do_something()
        return keyword

Is there some other way to find it out after super(MyForm, self).save() is called without checking for it explicitly before calling "super" like I am doing with "_new"?

like image 821
Muhammad Tahir Avatar asked Oct 28 '25 06:10

Muhammad Tahir


2 Answers

It's just the the .id (actually .pk) field. If it's None (potentially any 'falsy' value), then it's a new record and .save() will use INSERT. Otherwise it's the key to the existing record and it will use an UPDATE.

https://docs.djangoproject.com/en/1.8/ref/models/instances/#how-django-knows-to-update-vs-insert

like image 152
Javier Avatar answered Oct 30 '25 02:10

Javier


No, there is no other way to do it. ModelForm has no fields to indicate that object is created or updated. In fact you can pass to ModelForm the unsaved model as the instance and in this case the form will not construct the object at all:

form = MyForm(instance=MyModel())

So checking of the self.instance.pk is the only way for this task.

like image 31
catavaran Avatar answered Oct 30 '25 03:10

catavaran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!