简体   繁体   English

我应该在Django的save方法中的哪里使用原子事务?

[英]Where should I use atomic transactions in Django's save method?

Is this an appropriate use of atomic transactions? 这是对原子事务的适当使用吗? Why or why not? 为什么或者为什么不?

def save(self, **kwargs):
    try:
        with transaction.atomic:
            super(User, self).save(**kwargs)
            if self.image:
                img = Image.open(self.image.path)
                if img.height > 300 or img.width > 300:
                    output_size = (300, 300)
                    img.thumbnail(output_size)
                    img.save(self.image.path)
    except (OSError, IOError):
        self.image = None
        with transaction.atomic:
            super(User, self).save(update_fields=['image'])
        raise PValidationError('Image can`t be saved')

hi maybe you can use some thing like this: 嗨,也许你可以使用这样的事情:

class MyModel(models.Model):
    # model definition

    def save(self, *args, **kwargs):
        transaction.set_autocommit(False)
        try:
            super(MyModel, self).save(*args, **kwargs)
            # do_other_things
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()
        finally:
            transaction.set_autocommit(True)

However the better is used some thing like this: 但是更好的方法是使用这样的东西:

class MyModel(models.Model):
    # model definition

    @transaction.atomic
    def save(self, *args, **kwargs):
        super(MyModel, self).save(*args, **kwargs)

please for more information check: @transaction.atomic 请获取更多信息,请检查: @ transaction.atomic

good luck..!! 祝好运..!!

I think that you don't need any of the two atomic transactions actually. 我认为您实际上不需要两个原子事务中的任何一个。 The best example when atomic transaction can be used is transfering the money from one account to another, for example: 可以使用原子交易的最好例子是将钱从一个帐户转移到另一个帐户,例如:

def transfer_money(source_account, destination_account, quota):
    source_account.amount_of_money -= quota
    source_account.save()
    # K-BOOM
    destination_account.amount_of_money += quota
    destination_account.save()

What would happen if something went wrong in the # K-BOOM moment? 如果在# K-BOOM瞬间出了什么问题怎么办? One account would have less money and the second account would NOT have more as it should. 一个帐户将有较少的钱,而第二个帐户将没有应有的更多。

This is why we need the whole transfer_money function to be atomic: 这就是为什么我们需要整个transfer_money函数是原子的:

@transaction.atomic
def transfer_money(source_account, destination_account, quota):
    source_account.amount_of_money -= quota
    source_account.save()
    # K-BOOM
    destination_account.amount_of_money += quota
    destination_account.save()

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

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