简体   繁体   English

在django中使用pre_save时取消保存模型

[英]Cancel saving model when using pre_save in django

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. 但是当我调用A.save()时,我想确保该数字是素数(或其他条件),或者应该取消保存指令。

So how can I cancel the save instruction in the pre_save signal receiver? 那么如何取消pre_save信号接收器中的保存指令呢?

@receiver(pre_save, sender=A)
def save_only_for_prime_number(sender, instance, *args, **kwargs):
    # how can I cancel the save here?

See my another answer: https://stackoverflow.com/a/32431937/2544762 请参阅我的另一个答案: 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')

I'm not sure you can cancel the save only using the pre_save signal. 我不确定你是否只能使用pre_save信号取消保存。 But you can easily achieve this by overriding the save method: 但是您可以通过覆盖save方法轻松实现此目的:

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. 如@Raptor所述,调用者不知道保存是否成功。 If this is a requirement for you, take look at the other answer which forces the caller to deal with the "non-saving" case. 如果这是您的要求,请查看另一个强制呼叫者处理“非保存”情况的答案

If the data's always coming from a Form and you have a straightforward test for whether or not the save should occur, send it through a validator . 如果数据始终来自表单,并且您可以直接测试是否应该进行保存,请通过验证程序发送。 Note, though, that validators aren't called for save() calls originating on the backend. 但请注意,不会为在后端发起的save()调用调用验证器。 If you want those to be guarded as well, you can make a custom Field, say class PrimeNumberField(models.SmallIntegerField) If you run your test and raise an exception in the to_python() method of that custom field, it will prevent the save. 如果你想要保护那些,你可以创建一个自定义字段,比如class PrimeNumberField(models.SmallIntegerField)如果你运行测试并在该自定义字段的to_python()方法中引发异常,它将阻止保存。 You can also hook into the validation of a specific field by overriding any of several other methods on the Field, Form, or Model . 您还可以通过覆盖 Field,Form或Model上的任何其他方法来挂钩特定字段的验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM