django-rest-framework:DATA的serializer不更新型号 [英] django-rest-framework: serializer from DATA don't update model ID

查看:125
本文介绍了django-rest-framework:DATA的serializer不更新型号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的简单的序列化程序:

I've a simple serializer like this:

class CategoryCreationSerializer(serializers.ModelSerializer):

    class Meta:
        model = Category

类别有一个id字段(Django主键),我不知道Serializer没有更新它。

Category has an id field (Django primary key) and I don't get why the Serializer is not updating it.

场景:我有一个给定类别的BlogPost。我正在使用不同的类别(已经在数据库中创建)来更新BlogPost。因此,POST请求将使用新的类别JSON对象具有更新的所有BlogPost信息:

Scenario: I've a BlogPost with a given category. I'm updating the BlogPost with a different Category (already created on the database). So the POST request will have all the BlogPost information with the new Category JSON object with the updated id:

{
    "id": 1,
    "title": "My first blog post",
    "category": {
        "id": 3,
        "name": "Techology"
    }
}

问题是当我这样做:

The problem is that when I'm doing this:

category_data = data.get('category')
    if category_data is not None:
        category_serializer = CategoryCreationSerializer(data=category_data)
        if category_serializer.is_valid():
            blog_post.category = category_serializer.object

内部类别标题将被更新,但id字段将为NONE。
你能解释一下为什么吗?

inside category title will be updated but the id field will be NONE. Can you explain me why?

干杯,Emanuele。

Cheers, Emanuele.

推荐答案

这是官方的答案关于django rest-framework git仓库的我创建的问题 https://github.com/tomchristie/django-rest-framework/issues/2114

This is the official answer from the issue I created on django rest-framework git repository: https://github.com/tomchristie/django-rest-framework/issues/2114


简而言之,默认情况下,ModelSerializer将为该ID生成
只读字段。 (在通用视图中,您将看到
id由视图代码根据URL中的ID显式设置)
您需要显式声明序列化程序上的id字段
,你可以使它读写。

Short answer though is that by default ModelSerializer will generate a read-only field for the id. (In the generic views you'll see that the id is set explicitly by the view code, based on the id in the URL) You'll want to explicitly declare the id field on the serializer so that you can make it read-write.

所以我设法解决我的问题离开串行器像一个我的问题(没有 id = serializers.IntegerField()

So I managed to solve my problem leaving the Serializer like the one in my question ( without id = serializers.IntegerField() )

category_data = data.get('category', None)
if category_data is not None:
    category_serializer = CategoryCreationSerializer(blog_post.category, data=category_data)
    if category_serializer.is_valid():
        category_serializer.object.id = category_data.get("id", None)
        blog_post.category = category_serializer.object

这篇关于django-rest-framework:DATA的serializer不更新型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆