我最近将我的 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
}
这应该可以解决问题。
