完整性错误 - 1048,不能为空 - 无法保存validated_data



我想接受下面提到的来自用户的JSON数据,并希望将其保存到数据库(MySql(中。

{
"organisation_name":"abc pqr"
}

当我发出 POST 请求时,它会返回错误 -

IntegrityError at /api/organisation/
(1048, "Column 'organisation_id' cannot be null")
Request Method: POST
Request URL:    http://127.0.0.1:8000/api/organisation/
Django Version: 2.1.15
Exception Type: IntegrityError
Exception Value:    
(1048, "Column 'organisation_id' cannot be null")
Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py in execute, line 76
Python Executable:  /usr/local/bin/python
Python Version: 3.7.6
Python Path:    
['/app',
'/usr/local/lib/python37.zip',
'/usr/local/lib/python3.7',
'/usr/local/lib/python3.7/lib-dynload',
'/usr/local/lib/python3.7/site-packages']
Server time:    Sun, 5 Jan 2020 20:26:14 +0000

views.py

from typing import Optional, Any
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import JSONParser
from . import serializers

class OrganisationApiView(APIView):
def get(self, request, formate=None):
return Response({"message": "You are Cool!!"})
def post(self, request, formate=None):
serializer = serializers.OrganisationSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
organisation_saved = serializer.save()
organisation_name = serializer.validated_data.get('organisation_name')
message = f"Onboarding for {organisation_name} has been successful!."
return Response({'message': message, 'response': organisation_saved, 'status': status.HTTP_200_OK})
else:
return Response(serializer.error_messages)
def put(self, request, pk=None):
return Response({'message': 'PUT'})
def patch(self, request, pk=None):
return Response({'message': 'PATCH'})
def delete(self, request, pk=None):
return Response({'message': 'Delete'})

models.py

from django.core.validators import EmailValidator, validate_image_file_extension
from django.db import models

class BaseModel(models.Model):
""""This model will get the data/row created date for all the models defined in this model"""
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
class Meta:
abstract = True

class Organisation(models.Model):
"""This model will store the name of the tenant (organisation name). The data of this model could be further
utilized for creating a VM, Object Storage Bucket and a Database"""
organisation_id = models.BigIntegerField(primary_key=True, null=False)
organisation_name = models.CharField(max_length=255, null=False, unique=True, blank=False)

class Permission(models.Model):
"""This model list all the groups of the permissions. These permissions are further assigned to the users in User
model."""
permission_id = models.BigIntegerField(primary_key=True, null=False)
permission_name = models.CharField(max_length=100, null=False, blank=False)

class User(models.Model):
"""The data of the users belonging to the various Organisation will be stored here along with their login
credentials. This model also identifies the roles of the users in their respective organisation. The users
in the model can be classified or grouped according to the organisation."""
user_id = models.BigIntegerField(primary_key=True, null=False)
first_name = models.CharField(max_length=255, null=False, blank=False)
last_name = models.CharField(max_length=255, null=False, blank=False)
email = models.EmailField(
max_length=255,
unique=True,
null=False,
blank=False,
validators=[EmailValidator]
)
profile_picture = models.TextField(
max_length=255,
null=True,
blank=True,
validators=[validate_image_file_extension]
)
password = models.TextField(max_length=255, null=False, blank=False)
user_organisation = models.ForeignKey(Organisation, null=False, blank=False, on_delete=models.CASCADE)
user_role = models.ForeignKey(Permission, null=False, blank=False, on_delete=models.CASCADE)
is_active = models.BooleanField(default=False, blank=False, null=True)

serializers.py

from rest_framework import serializers
from .models import Organisation
class OrganisationSerializer(serializers.Serializer):
# organisation_id = serializers.IntegerField()
organisation_name = serializers.CharField(max_length=255, allow_null=False, allow_blank=False)
class Meta:
fields: '__all__'
def create(self, validated_data):
"""This method will insert Organisation Details into model Organisation"""
return Organisation.objects.create(**validated_data)

我已经覆盖了每个模型类中 Django 模型的默认主键。我只想接受用户的organisation_nameorganisation_id应该按照主键的原则生成。我不明白为什么它要求organisation_id,因为我已经提到它在我的 Django 模型中作为主键。我也尝试通过发送带有 JSON 中organisation_nameorganisation_id,但它仍然返回相同的错误。

如果你想让 Django 处理它的生成,你应该把它设置为Autofield,否则你要负责生成唯一 id 的函数。

https://docs.djangoproject.com/en/3.0/topics/db/models/#automatic-primary-key-fields

在你的大整数的情况下

organisation_id  = models.BigAutoField(primary_key=True)

最新更新