Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel saving model when using pre_save in django

Tags:

I have a model:

class A(models.Model):     number = models.IntegerField() 

But when I call A.save(), I want to ensure that number is a prime (or other conditions), or the save instruction should be cancelled.

So how can I cancel the save instruction in the pre_save signal receiver?

@receiver(pre_save, sender=A) def save_only_for_prime_number(sender, instance, *args, **kwargs):     # how can I cancel the save here? 
like image 888
Alfred Huang Avatar asked May 30 '14 07:05

Alfred Huang


People also ask

What is super save Django?

When you overwrite a function (of a class) you can call the function of the parent class using super . The save function in the models records the instance in the database. The first super(Review, self). save() is to obtain an id since it is generated automatically when an instance is saved in the database.

What is pre save signal in Django?

pre_save) is provoked just before the model save() method is called, or you could say model save method is called only after pre_save is called and done its job free of errors.

What is pre save and post in Django?

You can use pre_save for example if you have a FileField or an ImageField and see if the file or the image really exists. You can use post_save when you have an UserProfile and you want to create a new one at the moment a new User it's created.


2 Answers

See my another answer: https://stackoverflow.com/a/32431937/2544762

This case is normal, if we just want to prevent the save, throw an exception:

from django.db.models.signals import pre_save, post_save  @receiver(pre_save) def pre_save_handler(sender, instance, *args, **kwargs):     # some case     if case_error:         raise Exception('OMG') 
like image 106
Alfred Huang Avatar answered Sep 26 '22 07:09

Alfred Huang


I'm not sure you can cancel the save only using the pre_save signal. But you can easily achieve this by overriding the save method:

def save(self):     if some_condition:         super(A, self).save()     else:        return   # cancel the save 

As mentioned by @Raptor, the caller won't know if the save was successful or not. If this is a requirement for you, take look at the other answer which forces the caller to deal with the "non-saving" case.

like image 43
Seb D. Avatar answered Sep 22 '22 07:09

Seb D.