Django IntegrityError-1048,不能为空-无法保存已验证的\u数据

Django IntegrityError-1048,不能为空-无法保存已验证的\u数据,django,django-rest-framework,Django,Django Rest Framework,我想从用户那里接受下面提到的JSON数据,并将其保存到数据库(MySql)中 当我发出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 Exce

我想从用户那里接受下面提到的JSON数据,并将其保存到数据库(MySql)中

当我发出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
视图.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'})
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)

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)
型号.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'})
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)

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)
序列化程序.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'})
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)

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模型的默认主键。我只想接受用户提供的
organization\u name
,而
organization\u id
应该根据主键的原则生成。我不明白为什么它要求组织id,因为我已经在Django模型中将其作为主键提到过。我也尝试过用JSON中的
organization\u name
发送
organization\u id
,但它仍然返回相同的错误。

如果您希望Django处理其生成,则应将其设置为
Autofield
,否则您将负责生成唯一id的函数

在大整数的情况下

organisation_id  = models.BigAutoField(primary_key=True)

我按照您在我的组织模式中的建议进行了更改。此外,我还可以将对象插入数据库。但它也会生成一个错误,即TypeError:Organization类型的对象不可JSON序列化。