我在 Django 休息框架中收到完整性错误

I am getting Integrity error in django rest framework

我是 django 的初学者。我想添加一些 posts 和评论,但我收到了完整性错误。 没有评论模型,它以前可以工作,但不能一起工作。我已经删除了我的数据库和 makemigrations 并再次迁移。

post 款

from django.db import models
from django.conf import settings
# from django.contrib.auth import get_user_model


# User = get_user_model()

# Create your models here.
class Post(models.Model):
    user = models.ForeignKey(
        #to=User,
        to=settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='posts',
        null=True
    )
    content = models.CharField(
        max_length=150,
        blank=False
    )
    created = models.DateTimeField(
        auto_now=True
    )
    liked_by = models.ManyToManyField(
         #to=User,
         to=settings.AUTH_USER_MODEL,
         related_name='liked_posts',
         blank=True
    ) 

post 序列化器

 from rest_framework import serializers
from .models import Post
from ..comment.serializers import CommentSerializer


class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        comments = CommentSerializer(source='comments.content')
        fields = [
            'id',
            'user',
            'content',
            'comments',
            'created',
            'liked_by',
        ]

comment.models

from django.db import models
from django.conf import settings
from apps.post.models import Post


# Create your models here.
class Comment(models.Model):
    user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comment', null=True)
    post = models.ForeignKey(to=Post, on_delete=models.SET_NULL, related_name='comment', null=True)
    content = models.CharField(max_length=150)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'Comment by: {self.user}'

评论序列化器

from rest_framework import serializers
from .models import Comment


class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = ['id', 'user', 'post', 'content', 'created']

您需要正确传递 PostSerializer 元 class 中的 CommentSerializer 字段。

from rest_framework import serializers
from .models import Post
from .comment.serializers import CommentSerializer
class PostSerializer(serializers.ModelSerializer):
    comments = CommentSerializer(many=True)
    class Meta:
        model = Post
        
        fields = [
            'id',
            'user',
            'content',
            'comments',
            'created',
            'liked_by',
            'comments',
        ]