Django postgres 给出 psycopg2.errors.NotNullViolation: "id_id" 列中的空值违反了非空约束

Django postgress gives psycopg2.errors.NotNullViolation: null value in column "id_id" violates not-null constraint

下面是我的模型 Windows10,postgress 12,django 3.0.7,python3.7.6

class User(AbstractBaseUser, PermissionsMixin):
    email = models.CharField(max_length=30)
    password = models.CharField(max_length=4000)

    first_name = models.CharField(default='', max_length=15)
    last_name = models.CharField(default='', max_length=15)
    login = models.CharField(max_length=15)
    age = models.IntegerField()
    street = models.CharField(blank=True, max_length=255)
    city = models.CharField(blank=True, max_length=255)
    zip = models.CharField(blank=True, max_length=10)
    role = models.CharField(default='', max_length=10)

    USERNAME_FIELD = 'email'

当我发出 post 请求时,我遇到了以下错误

File "C:\Users\Akila\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.NotNullViolation: null value in column "id_id" violates not-null constraint
DETAIL:  Failing row contains (null, default).

这是正在调用的我的注册视图。

@staticmethod

@api_view(['POST'])

def sign_up(request):

    logging.debug("Trying to register a new user")

    data = common_methods.get_request_data(request)

    print(data)

    if check_user_exists(data['email']):

        return JsonResponse({'message': 'User with this email already exists'},status=status.HTTP_400_BAD_REQUEST)

    print(data['email'])

    create_user(data['email'], data['password'], data['fullName'])


    refresh = CustomTokenObtainPairSerializer.get_token(
        get_user_by_email(email=data['email']))
    return JsonResponse({'token': {
        'access_token': str(refresh.access_token),
        'expires_in': str(refresh.access_token.lifetime.seconds),
        'refresh_token': str(refresh)
    }})

实际上我的 create_user() 方法中有这个

 user_settings = UserSettings(id=user.id, theme='default')
 user.save()
 user_settings.save()

根据上面的代码 user.id 实际上是空的。 id 在用户保存到数据库后分配。 必须将其更改为以下才能使其正常工作

try:
    user.save()
except Exception as e:
    print(str(e))
    raise Exception("Sorry couldn't save the user with email : " + user.email)

if check_user_exists(user.email):
    user = get_user_by_email(email=user.email)
    user_settings = UserSettings(id_id=user.id, theme='default')
    user_settings.save()
else:
    raise Exception("Sorry couldn't find the user with email : " + user.email)