Django Rest Framework POST 失败:列 "cat_id" 中的空值违反了 not-null 约束

Django Rest Framework POST fails: null value in column "cat_id" violates not-null constraint

我最近将我的视图转换为通用 class-based 视图,但是我刚刚注意到 POST 请求在具有 foreign-keys 的 类 上失败。下面是我的代码,后面是错误信息。

models.py

class Category(models.Model):
    name = models.CharField(max_length=25, blank=False)

    class Meta:
        ordering = ('id',)


class Task(models.Model):
    name = models.CharField(max_length=25, blank=False)
    cat = models.ForeignKey(Category, on_delete=models.CASCADE)

    class Meta:
        ordering = ('id',)

serializers.py

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ('id', 'name', 'cat_id')


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'name')

views.py

class TaskList(generics.ListCreateAPIView):
    """
    List all Tasks (OR for specified cat_id)
    """
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
    filter_fields = ('cat_id',)

urls.py

path('tasks/', views.TaskList.as_view()),

返回错误

django.db.utils.IntegrityError: null value in column "cat_id" violates not-null constraint
DETAIL:  Failing row contains (51, buy-some, null).

请求内容:JSONObject

{
    "name": "buy-some",
    "cat_id": 1
}

此外,Content-Type、Acceptheaders设置为application/json

存在 id=1 的类别

可能您想要的是将 TaskSerializer 中的字段 cat 定义为 PrimaryKeyRelatedField(documentation here),在您的情况下为:

class TaskSerializer(serializers.ModelSerializer):
    cat = PrimaryKeyRelatedField(queryset=Category.objects.all())
    class Meta:
        model = Task
        fields = ('id', 'name', 'cat')

然后在您的请求中,只需在 "cat" 字段中发送 pk,如下所示:

{
    "name": "buy-some",
    "cat": 1
}

这应该可以解决问题。