无法使用 JSON 发送 POST

Can't send a POST using JSON

我正在使用带有 rest 框架的 django 应用程序工作。我需要通过 json 在 table 中添加一个新行,但是这个 table 是另一个 table.

的子项

当我尝试发送 "POST" 应用程序时 returns 这个错误: ... 不能为 NULL

图片 > https://dl.dropboxusercontent.com/u/31258353/addnewrow.jpg

型号:

 # Create your models here.
    class sequence(models.Model):
        number = models.CharField(max_length=3)
        word = models.CharField(max_length=1)
        name = models.CharField(max_length=100)


    class localization(models.Model):
        sequence = models.ForeignKey(sequence)
        init = models.CharField(max_length=3)
        name = models.CharField(max_length=100)

表格:

    class sequenceform(forms.ModelForm):
        class Meta:
            model = sequence


    class localizationform(forms.ModelForm):
        class Meta:
            model = localization

序列化:

class sequenceserializer(serializers.ModelSerializer):
    class Meta:
        model = sequence
        fields = ("pk","number","word","name")

class localizationserializer(serializers.ModelSerializer):
    class Meta:
        model = localization
        fields = ("id","init","name")

查看:

@api_view(['GET', 'POST'])
def sequencelistjson(request, format=None):
    if request.method == 'GET':
        prj = sequence.objects.all()
        serializer = sequenceserializer(prj, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = sequenceserializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'POST'])
def localizationlistjson(request, seq_id, format=None):
    if request.method == 'GET':
        seq = get_object_or_404(sequence, pk=seq_id)
        loc = seq.localization_set.order_by('init')
        serializer = localizationserializer(loc, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = localizationserializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

您正在尝试创建一个 localization 对象,但它要求 sequence 存在(被 ForeignKey 看到)。

在您的序列化程序中,您没有为 sequence 指定一个字段,因此 Django REST 框架不知道需要一个字段。因为您没有在其他地方关联 sequence,所以当 Django REST 框架尝试创建 localization 对象时,sequence 将作为 NULL 发送。这是不允许的,因为 ForeignKey 没有设置 null=True(这是必需的)。

如果实际上不需要,您可以通过将 null=True 添加到 sequence 字段来解决此问题。另一个选项(很可能是您想要的)是在序列化程序的 Meta.fields 选项中包含 sequence 字段。