Equivalent of get_or_create for adding users

后端 未结 4 1831
北荒
北荒 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 02:43

    I don't think so. But you can proxify the Django User:

    class MyUser(User):
        class Meta:
            proxy = True
    
        def get_or_create(self, username, email, password, *args, **kwargs):
            try:
                new_user = User.objects.create_user(username, email, password)
            except IntegrityError:
                return User.objects.get(username=username, email=email)
            else:
                new_user.first_name = kwargs['first_name'] # or what you want
                ...etc...
    
            return new_user
    

提交回复
热议问题