Django IntegrityError:NOT NULL 约束失败

问题描述 投票:0回答:1

我想创建模型

Serializers
和所有必要的代码。我想解决 API 课程的 Coursera 项目评估。

Error: django.db.utils.IntegrityError: NOT NULL constraint failed: LittleLemonAPI_menuitem.category_id

当我在

depth = 1
中定义
MenuItemSerializer
并创建新的菜单项时,就会发生这种情况。如果我删除
depth = 1
category = CategorySerializer
就不会出现错误。但是表类别未填充。

serializers.py

from rest_framework import serializers, validators
from .models import Category, MenuItem, Cart, Order, OrderItem
from django.contrib.auth.models import User, Group, Permission

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ['id', 'slug', 'title']

        validators = [
            validators.UniqueTogetherValidator(
                queryset=Category.objects.all(),
                fields=('title',),
                message="Category must be unique"
            )
        ]

class MenuItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = MenuItem
        category = CategorySerializer()
        fields = ['id', 'title', 'price',
                  'featured', 'inventory', 'category',]
        depth = 1

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'groups',]
        depth = 1

class CartSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cart
        user = UserSerializer()
        menuitem = MenuItemSerializer()
        fields = ['id', 'user', 'menuitem', 'quantity', 'unit_price', 'price']
        depth = 1
        validators = [
            validators.UniqueTogetherValidator(
                queryset=MenuItem.objects.all(),
                fields=('id',),
                message="Menuitem should be unique in this curt"
            ),
            validators.UniqueTogetherValidator(
                queryset=User.objects.all(), fields=('id'), message="User should be unique")
        ]

class OrderSerilizer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ['id', 'user', 'delivery_crew', 'status', 'total', 'date']
        depth = 1

class OrderItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderItem
        fields = ['id', 'order', 'menuitem', 'quantity', 'unit_price', 'price']
        depth = 1
        validators = [
            validators.UniqueTogetherValidator(
                queryset=Order.objects.all(),
                fields=('id',)
            ),
            validators.UniqueTogetherValidator(
                queryset=MenuItem.objects.all(),
                fields=('id',)
            )
        ]

models.py

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Category(models.Model):
    slug = models.SlugField()
    title = models.CharField(max_length=255, db_index=True)

class MenuItem(models.Model):
    title = models.CharField(max_length=255, db_index=True)
    price = models.DecimalField(max_digits=6, decimal_places=2, db_index=True)
    featured = models.BooleanField(db_index=True)
    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    inventory = models.IntegerField()

class Cart(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    menuitem = models.ForeignKey(MenuItem, on_delete=models.CASCADE)
    quantity = models.SmallIntegerField(),
    unit_price = models.DecimalField(max_digits=6, decimal_places=2)
    price = models.DecimalField(max_digits=6, decimal_places=2)

    class Meta:
        unique_together = ('menuitem', 'user')

class Order(models.Model):
    user = models.ForeignKey(User, models.CASCADE)
    delivery_crew = models.ForeignKey(
        User, on_delete=models.SET_NULL, related_name='delivery_crew', null=True)
    status = models.BooleanField(db_index=True, default=0)
    total = models.DecimalField(max_digits=6, decimal_places=2)
    date = models.DateField(db_index=True)

class OrderItem(models.Model):
    order = models.ForeignKey(User, on_delete=models.CASCADE)
    menuitem = models.ForeignKey(MenuItem, on_delete=models.CASCADE)
    quantity = models.SmallIntegerField()
    unit_price = models.DecimalField(max_digits=6, decimal_places=2)
    price = models.DecimalField(max_digits=6, decimal_places=2)

    class Meta:
        unique_together = ('order', 'menuitem')
python django django-rest-framework relational-database
1个回答
0
投票

错误:django.db.utils.IntegrityError:NOT NULL 约束失败:LittleLemonAPI_menuitem.category_id

此错误告诉您在创建菜单项时必须提供类别 ID。

另一个错误是在写入序列化器中使用深度。删除它和元中的类别,你应该没问题。

使用此序列化器:

class MenuItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = MenuItem
        fields = ['id', 'title', 'price',
                  'featured', 'inventory', 'category',]

然后你只需传递一个包含所有这些字段的字典:标题、价格、特色、库存和有效的类别 ID。

© www.soinside.com 2019 - 2024. All rights reserved.