LoginSignup
1
0

More than 1 year has passed since last update.

django transaction.atomic() + 自前エラークラス

Posted at

を書くんだよ

tryの中でこけると、user.save()はrollbackされる。
うまくいったところだけ保存したいならwith transaction.atomic()は外す


class UserNameError(BaseException):
    """ UserName must contain two '@' s. An example is 'MailAddress@Organization_name'"""
    pass

...

    if organization.name != params["name"]:
        users = User.objects.filter(organization_id=organization_id)
        try:
            with transaction.atomic():
                for user in users:
                    user_name = user.username
                    if (ユーザー名の形式をチェックする条件):
                        user.username = params["name"]
                        user.save()
                    else:
                        # usernameが形式通りではないユーザー名を変更しようとした時は、何もしない
                        raise UserNameError(f"""UserName {params["name"]} はユーザーネームが形式通りではないと思います的な英語などのメッセージ""")
        except Exception:
            return None

...

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0