Equivalent of get_or_create for adding users

后端 未结 4 1824
北荒
北荒 2021-02-07 02:05

Is there a simpler way to add a user than with the following pattern?

    try:
        new_user = User.objects.create_user(username, email, password)
    except          


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-07 03:01

    It is better not to catch IntegrityError as it can happen for other reasons. You need to check if user exists, excluding the password. If user already exists, set the password.

    user, created = User.objects.get_or_create(username=username, email=email)
    if not created:
        user.set_password(password)
    

提交回复
热议问题