django休息框架模型序列化程序 - 读取嵌套,写入 [英] django rest framework model serializers - read nested, write flat

查看:104
本文介绍了django休息框架模型序列化程序 - 读取嵌套,写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我的客户试图写一个表示,其中包含一个fk的列表

I have a situation where my client is attempting to write a representation that includes a list of fk's

{
languages: [1]
last_name: "Beecher"
settings: 1
state: "NY"
}

但是,当阅读它时,我希望有一个嵌套的表示来缩小回合

But when reading it in, I'd like to have a nested representation to cut back on roundtrips

{
languages: [{id:1, created:2013-07-21T01:38:33.569Z, modified:2013-07-21T01:38:33.569Z, language:testing}]
last_name: "Beecher"
settings: {
created: "2013-07-20T22:04:17.998Z"
email_blog: false
email_booking_accepted_denied: false
email_booking_request: false
email_friend_joined: false
email_groups_added_network: false
email_new_review: false
email_news: false
email_upcoming_booking_remind: false
id: 1
mobile_booking_accepted_denied: false
mobile_booking_request: false
mobile_friend_joined: false
mobile_groups_added_network: false
mobile_new_review: false
mobile_upcoming_booking_remind: false
modified: "2013-07-20T22:04:18.000Z"
user: 1
}
state: "NY"
}

使用模型序列化器并且深度= 1,读数是没有问题的 - 但尝试写入会给出一个错误ValueError('实例应该是一个queryset或其他可迭代的许多= True')
当尝试检查许多相关字段 iter

Reading is no problem using a model serializer and depth=1 - but attempting to write gives an error "ValueError('instance should be a queryset or other iterable with many=True')" When attempting to check a many related field for iter

相反,关闭深度使写作工作正如我所愿,但阅读不好。

Conversely, turning off depth makes writing work just as I'd like, but reading is no good.

是有什么我完全错过这里?似乎应该是一个简单的改变,但是我只能得到一个或另一个工作

Is there something I'm totally missing here? It seems like it should be a simple change, but I can only get one or the other working

推荐答案

感谢以前的帖子,我根据 get_serializer_class 为此提供了类似的解决方案。

Thanks to previous posts, I went with a similar solution based off get_serializer_class for this.

我还想根据方法更改序列化器类。

I also wanted to be able to change the serializer class depending on method.

首先,我添加了一个属性到视图类与字典映射请求方法到序列化器类。

First, I added an attribute to the view class with a dictionary mapping request methods to serializer classes.

 serializer_classes = {
     'GET': NestedSerializer,
     'POST': FlatSerializer
 }

然后,我定义了一个mixin来使用我想要的行为。

Then, I defined a mixin to use where I want this behavior.

class SwappableSerializerMixin(object):
    def get_serializer_class(self):
        try:
            return self.serializer_classes[self.request.method]
        except AttributeError:
            logger.debug('%(cls)s does not have the required serializer_classes'
                         'property' % {'cls': self.__class__.__name__})
            raise AttributeError
        except KeyError:
            logger.debug('request method %(method)s is not listed'
                         ' in %(cls)s serializer_classes' %
                         {'cls': self.__class__.__name__,
                          'method': self.request.method})
            # required if you don't include all the methods (option, etc) in your serializer_class
            return super(SwappableSerializerMixin, self).get_serializer_class() es

这篇关于django休息框架模型序列化程序 - 读取嵌套,写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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