IntegrityError - 1048, не может быть пустым - невозможно сохранить validated_data - PullRequest
0 голосов
/ 05 января 2020

Я хочу принять указанные ниже данные 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)

сериализаторов .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_name от пользователя, а organisation_id должен быть сгенерирован в соответствии с принципами Первичный ключ . Я не понимаю, почему он запрашивает идентификатор_организации, поскольку я уже упоминал его как Первичный ключ в моей Django модели. Я также пытался отправить organisation_id с organisation_name в JSON, но он по-прежнему возвращает ту же ошибку.

1 Ответ

0 голосов
/ 05 января 2020

Вам следует установить значение Autofield, если вы хотите, чтобы Django обрабатывал его генерацию, в противном случае вы несете ответственность за функцию, которая генерирует уникальные идентификаторы

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

В вашем случае большой int

organisation_id  = models.BigAutoField(primary_key=True)
...