gpt4 book ai didi

python - Django Rest Framework POST 失败 : null value in column "cat_id" violates not-null constraint

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:59 29 4
gpt4 key购买 nike

我最近将我的 View 转换为通用的基于类的 View ,但是我刚刚注意到 POST 请求在具有外键的类上失败。以下是我的代码,后面是错误信息。

模型.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',)

序列化器.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).

请求内容:JSON 对象

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

此外,Content-Type、Accept header 设置为 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
}

这应该可以解决问题。

关于python - Django Rest Framework POST 失败 : null value in column "cat_id" violates not-null constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53309082/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com