Apostolos
Apostolos

Reputation: 8101

Making sure django model was properly saved

When saving a django model using it's save method is there any way to make sure nothing happened during save and send a message to the user? I was thinking of the message framework and try except block?

try:
    model.save()
    add success message to message framework
except DatabaseError:
    add error message to message framework
except TransactionManagementError:
    add error message

Is this the right way to do that?Also which exception is more likely to be raised when trying to save a new instance of a model?I fairly new to django so be kind :)

Upvotes: 4

Views: 5541

Answers (2)

daveoncode
daveoncode

Reputation: 19578

My approach is to use a base abstract model that all my models extend and in which I override the save method in order to catch exceptions and rollback transactions:

class AbstractModel(models.Model):
    class Meta:
        abstract = True

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        try:
            super(AbstractModel, self).save(force_insert, force_update, using, update_fields)
        except IntegrityError as saveException:
            logger.exception('Rolling back transaction due to an error while saving %s...' % self.__class__.__name__)
            try:
                transaction.rollback()
            except Exception as rollbackException:
                logger.exception('Unable to rollback!')

Upvotes: 3

Udi
Udi

Reputation: 30472

You would generally want to divide this to two problems:

Upvotes: 1

Related Questions