django-rest-framework序列化器在多个视图中的不同字段 [英] django-rest-framework serializer different fields in multiple views

查看:234
本文介绍了django-rest-framework序列化器在多个视图中的不同字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django的新手,找不到解决我问题的方法。

I am new at Django and couldn't find solution for my problem.

问题是要强制特定的序列化程序在使用情况下包括不同数量的字段不同的看法。我想在第一个视图中使用 id字段,在第二个视图中使用 id和 name字段。

The problem is to force specific serializer for include different amount of fields in case of utilizing different views. I would like to use 'id' field in my 1st view, and in 2nd view - 'id' and 'name' fields.

这是我的模型。py

class Processing(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField()
    description = models.CharField()

这是我的serializer.py

And here is my serializer.py

class ProcessingSerializer(serializers.ModelSerializer):
    id = serializers.ModelField(model_field=Processing()._meta.get_field('id'))
    class Meta:
        model = Processing
        fields = ('id', 'name')

任何帮助都将受到欢迎。

Any help will be welcome.

推荐答案

何时有人刚开始使用DRF,一个常见的错误是试图让相同的Serializer在阳光下进行所有操作。当然,我本人就是沿着那条路走的。

When someone just starts using DRF, a common mistake is to try to make the same Serializer do everything under the sun. Certainly I went down that path myself.

,但是当您使用多序列化程序执行不同的任务时,生活变得简单得多。您可以使用 get_serializer_class 方法轻松切换序列化程序。这是手册中的一个示例,显示了如何为管理员使用,为普通用户使用另一个

but life becomes a lot simpler when you use mutiple serializers for different tasks. You can easily switch serializers using the get_serializer_class method. Here is an example right from the manual that shows how to use one for admins and another for ordinary users

def get_serializer_class(self):
    if self.request.user.is_staff:
        return FullAccountSerializer
    return BasicAccountSerializer

有时您想使用一个序列化程序来存储列表,而使用另一个序列化程序来提供详细信息。尝试这样的事情:

Sometimes you want to use a single serializer for lists and another one for when providing details. Try something like this:

def get_serializer_class(self):
    if self.action == 'retrieve':
        return serializers.PlayerDetailSerializer
    else : 
        return serializers.PlayerSerializer

这样生活要简单得多。

这篇关于django-rest-framework序列化器在多个视图中的不同字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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