1
我正在爲特定的json輸入使用django-rest-framework創建api端點。我有兩個相關的模型,像這樣(假設後只能有一個類別):django rest框架嵌套對象獲取或創建行爲
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'參數對我來說很重要,我希望數據在我的db上使用json中提供的精確pk創建。現在,如果我發佈了一個post請求,並且沒有ID爲10的文章和id爲15的類別,那麼所有的都很好,並且數據被寫入db新的記錄被插入,但是如果有任何rest-framework返回類似[ '帖子id 10已經存在'],我想匹配記錄根據輸入更新。我怎樣才能做到這一點?
如果我添加put/patch然後rest框架需要look_up字段和模型爲我創建的視圖,因爲我使用此輸入與多個模型,我不能提供他們.. – balkan