Django Rest框架 - 读取嵌套数据,写入整数 [英] Django Rest Framework - Read nested data, write integer

查看:138
本文介绍了Django Rest框架 - 读取嵌套数据,写入整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我对Django Rest框架非常满意,这就是为什么我几乎不敢相信在代码库中有这么大的遗漏。希望有人知道如何支持这一点:

  class PinSerializer(serializers.ModelSerializer):
item = ItemSerializer (read_only = True,source ='item')
item = serializers.IntegerSerializer(write_only = True)

class Meta:
model = Pin

与目标

 目标是读取:
{pin:item:{name:'a',url:'b'}}
但是使用id
{pin:item:10}

另一种替代方法是使用两个序列化程序,但这看起来像一个非常难看的解决方案:
django休息框架模型序列化程序 - 读取嵌套,写入平面< a>

假设您使用OneToOneField或ForeignKey将您的Pin与您的项目相关联,Django将该关系存储为 item_id ,但通常会将项目抽象为项目。您可以利用这一点了解一个Python对象不能具有相同名称的两个属性(您的代码中遇到的问题)。



简单将 _id 添加到您的写入属性的名称,任何写入将设置底层关系,而任何读取将使用抽象对象。您的最终代码将是:

  class PinSerializer(serializers.ModelSerializer):
item = ItemSerializer(read_only = True, source ='item')
item_id = serializers.IntegerField(write_only = True)

class Meta:
model = Pin
/ pre>

注意1:我还将 serializers.IntegerSerializer 更改为 serializers.IntegerField ,因为我认为这一定是一个错字。



注意2:我实际上发现Django Rest是非常直观的,没有指定Item序列号的Pin序列化器将item_id替换为item:< id> 而不是item_id:< id> code>,但这是旁边。


So far I'm extremely happy with Django Rest Framework, which is why I alsmost can't believe there's such a large omission in the codebase. Hopefully someone knows of a way how to support this:

class PinSerializer(serializers.ModelSerializer):
    item = ItemSerializer(read_only=True, source='item')
    item = serializers.IntegerSerializer(write_only=True)

    class Meta:
        model = Pin

with the goal

The goal here is to read:
{pin: item: {name: 'a', url: 'b'}}
but to write using an id
{pin: item: 10}

An alternative would be to use two serializers, but that looks like a really ugly solution: django rest framework model serializers - read nested, write flat

解决方案

Assuming you are using a OneToOneField or ForeignKey to relate your Pin to your Item, Django stores the relation as item_id, but often abstracts the Item as item. You can take advantage of this to get around the fact that a Python object cannot have two attributes with the same name (a problem you would encounter in your code).

Simply add _id to the name of your write attribute and any writes will set the underlying relation, while any reads will use the abstracted object. Your final code will be:

class PinSerializer(serializers.ModelSerializer):
    item = ItemSerializer(read_only=True, source='item')
    item_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = Pin

Note 1: I also changed serializers.IntegerSerializer to serializers.IntegerField, since I think that must have been a typo.

Note 2: I actually find it rather unintuitive that Django Rest is set up such that a Pin serializer without an Item serializer specified returns the item_id as "item": <id> and not "item_id": <id>, but that is beside the point.

这篇关于Django Rest框架 - 读取嵌套数据,写入整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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