2
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.
5
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
- [Django]-Django Validators in Serializer vs Constraints in Models
- [Django]-Using Google App Engine Queues service with Django
- [Django]-Django ModelForm initial or custom field value
- [Django]-Python: list to JSON
Source:stackexchange.com