【发布时间】:2014-02-17 12:11:26
【问题描述】:
我正在使用 django-rest-framework 为特定的 json 输入创建一个 api 端点。我有两个这样的相关模型(假设帖子只能有一个类别):
class Category(models.Model):
name = models.CharField(max_length=10)
slug = models.SlugField()
class Post(models.Model):
category = models.ForeignKey()
title = models.CharField(max_length=100)
text = models.CharField(max_length=256)
我的序列化器是简单的模型序列化器:
class CategorySerializer(ModelSerializer):
id = serializers.IntegerField(required=True)
class Meta:
model = Category
class PostSerializer(ModelSerializer):
id = serializers.IntegerField(required=True)
category = CategorySerializer()
class Meta:
model = Post
我的 api 视图也很简单:
class PostAPIView(mixins.CreateModelMixin, GenericAPIView):
serializer_class = PostSerializer
permission_classes = (IsAuthenticated,)
现在为了创建帖子,我需要像这样解析 json 输入:
{
"id": 10,
"pk": 10
"title": "Some title",
"text": "Some text",
"category": {
"id": 15,
"pk": 15
"name": "Best category",
"slug": "best-category"
}
}
这里的“pk”参数对我来说至关重要,我希望使用 json 中提供的精确 pk 在我的数据库上创建数据。现在,如果我发出一个帖子请求,并且没有 id:10 的帖子和 id:15 的类别,一切都很好,并且数据被写入 db 新记录被插入,但是如果有任何时候 rest-framework 返回类似 [ 'Post id 10 已经存在'],我想根据输入更新匹配记录。我该怎么做?
【问题讨论】:
标签: django django-rest-framework