500错误:“ timeline_id”列中的空值违反了非空约束

时间:2019-11-27 19:48:55

标签: python django reactjs django-rest-framework

我目前是一名学生,正在尝试使用python / django和React创建一个全栈Web应用程序。在构建后端时,我遇到了一个问题,当发布包含关联的对象时,在响应负载和数据库之间会丢失关联的ID。我知道状态正在按需更新,并且可以创建其他不使用后端关联的对象而不会出现问题。我认为我的错误一定是在我制作的模型或序列化器中的某个地方,但是到目前为止我还没有找到它。

500错误消息:

Integrity error at "api/v1/event"
null value in column "timeline_id" violates not-null constraint
DETAIL: failing row contains (index_id, junk_data, junk_data, 1, null)

我的模特:

from django.db import models

class Timeline(models.Model):
    name = models.CharField(max_length=50, default='n/a')

    def __str__(self):
        return self.name


class Event(models.Model):
    name = models.CharField(max_length=25, default='n/a')
    description = models.CharField(max_length=150, default='n/a')
    coordinate = models.IntegerField(default=0)
    timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE, related_name="events")

    def __str__(self):
        return self.name


class Note(models.Model):
    article = models.TextField(default='n/a')
    event  = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='notes')
    # event = models.ManyToManyField(Event)

    def __str__(self):
        return self.article

我的观点:

from rest_framework import viewsets

from .serializers import TimelineSerializer, EventSerializer, NoteSerializer
from .models import Timeline, Event, Note

class TimelineView(viewsets.ModelViewSet):
    queryset = Timeline.objects.all()
    serializer_class = TimelineSerializer

class EventView(viewsets.ModelViewSet):
    queryset = Event.objects.all()
    serializer_class = EventSerializer

class NoteView(viewsets.ModelViewSet):
    queryset = Note.objects.all()
    serializer_class = NoteSerializer

我的序列化器:

from rest_framework import serializers

from .models import Timeline, Note, Event

class NoteSerializer(serializers.ModelSerializer):

    class Meta:
        model = Note
        fields = ('id', 'title', 'article')


class EventSerializer(serializers.ModelSerializer):
    notes = NoteSerializer(many=True, read_only=True)

    class Meta:
        model = Event
        fields = ('id', 'name', 'description', 'coordinate', 'notes')


class TimelineSerializer(serializers.ModelSerializer):
    events = EventSerializer(many=True, read_only=True)

    class Meta:
        model = Timeline
        fields = ('id', 'name', 'events')

链接到github仓库: https://github.com/dantehollo/world_builder_site

我正在linux(ubuntu 18.04.3)上使用python 3.6.8

我试图尽可能具体和简短。如果有遗漏,请告诉我,我一看到要求就会尽快将其发布。非常感谢您对这是什么,它为什么发生以及如何避免的任何帮助,谢谢。

1 个答案:

答案 0 :(得分:2)

根据您的Event模型timeline属性(也是外键),该属性是必需的,不能为null。而且您忘了将此timeline添加到EventSerializer的字段中:

class EventSerializer(serializers.ModelSerializer):
    notes = NoteSerializer(many=True, read_only=True)

    class Meta:
        model = Event
        fields = ('id', 'name', 'description', 'coordinate', 'notes', 'timeline')

现在,如果您没有在请求中发送timeline,则DRF会向ValidationError发出您必须包含它的信息。