[英]Django Rest Framework POST fails: null value in column "cat_id" violates not-null constraint
I've recently converted my views to generic class-based views, however I've just noticed that POST requests fail on classes that have foreign-keys.我最近将我的视图转换为基于类的通用视图,但是我刚刚注意到 POST 请求在具有外键的类上失败。 The following is my code, followed by the error message.
以下是我的代码,后面是错误信息。
models.py模型.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序列化程序.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视图.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网址.py
path('tasks/', views.TaskList.as_view()),
Error returned返回错误
django.db.utils.IntegrityError: null value in column "cat_id" violates not-null constraint
DETAIL: Failing row contains (51, buy-some, null).
REQUEST content: JSON Object请求内容:JSON 对象
{
"name": "buy-some",
"cat_id": 1
}
Additionally, Content-Type, Accept headers are set to application/json .此外, Content-Type、Accept标头设置为application/json 。
Category with id=1 exists存在 id=1 的类别
Probably what you want is to define the field cat
in your TaskSerializer
to be a PrimaryKeyRelatedField
(documentation here) , in your case would be:可能您想要的是将
TaskSerializer
的字段cat
定义为PrimaryKeyRelatedField
(documentation here) ,在您的情况下是:
class TaskSerializer(serializers.ModelSerializer):
cat = PrimaryKeyRelatedField(queryset=Category.objects.all())
class Meta:
model = Task
fields = ('id', 'name', 'cat')
Then in your request just send the pk in the "cat"
field like so:然后在您的请求中,只需在
"cat"
字段中发送 pk,如下所示:
{
"name": "buy-some",
"cat": 1
}
This should do the trick.这应该可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.