Django休息框架,在同一个ModelViewSet中使用不同的序列化器

时间:2014-03-24 17:54:35

标签: django serialization django-rest-framework

我想提供两种不同的序列化程序,但能够从ModelViewSet的所有功能中受益:

  • 在查看对象列表时,我希望每个对象都有一个重定向到其详细信息的URL,并且使用目标模型的__unicode __显示所有其他关系;

示例:

{
  "url": "http://127.0.0.1:8000/database/gruppi/2/",
  "nome": "universitari",
  "descrizione": "unitn!",
  "creatore": "emilio",
  "accesso": "CHI",
  "membri": [
    "emilio",
    "michele",
    "luisa",
    "ivan",
    "saverio"
  ]
}
  • 查看对象的详细信息时,我想使用默认的HyperlinkedModelSerializer

示例:

{
  "url": "http://127.0.0.1:8000/database/gruppi/2/",
  "nome": "universitari",
  "descrizione": "unitn!",
  "creatore": "http://127.0.0.1:8000/database/utenti/3/",
  "accesso": "CHI",
  "membri": [
    "http://127.0.0.1:8000/database/utenti/3/",
    "http://127.0.0.1:8000/database/utenti/4/",
    "http://127.0.0.1:8000/database/utenti/5/",
    "http://127.0.0.1:8000/database/utenti/6/",
    "http://127.0.0.1:8000/database/utenti/7/"
  ]
}

我设法按照以下方式完成所有这些工作:

serializers.py

# serializer to use when showing a list
class ListaGruppi(serializers.HyperlinkedModelSerializer):
    membri = serializers.RelatedField(many = True)
    creatore = serializers.RelatedField(many = False)

    class Meta:
        model = models.Gruppi

# serializer to use when showing the details
class DettaglioGruppi(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Gruppi

views.py

class DualSerializerViewSet(viewsets.ModelViewSet):
    """
    ViewSet providing different serializers for list and detail views.

    Use list_serializer and detail_serializer to provide them
    """
    def list(self, *args, **kwargs):
        self.serializer_class = self.list_serializer
        return viewsets.ModelViewSet.list(self, *args, **kwargs)

    def retrieve(self, *args, **kwargs):
        self.serializer_class = self.detail_serializer
        return viewsets.ModelViewSet.retrieve(self, *args, **kwargs)

class GruppiViewSet(DualSerializerViewSet):
    model = models.Gruppi
    list_serializer = serializers.ListaGruppi
    detail_serializer = serializers.DettaglioGruppi

    # etc.

基本上我检测用户何时请求列表视图或详细视图并更改serializer_class以满足我的需要。我对这段代码并不是很满意,它看起来像是一个肮脏的黑客,最重要的是,如果两个用户在同一时刻请求列表和详细信息会怎样?

是否有更好的方法可以使用ModelViewSets实现此目标,还是必须使用GenericAPIView后退?

修改
以下是使用自定义基础ModelViewSet

的方法
class MultiSerializerViewSet(viewsets.ModelViewSet):
    serializers = { 
        'default': None,
    }

    def get_serializer_class(self):
            return self.serializers.get(self.action,
                        self.serializers['default'])

class GruppiViewSet(MultiSerializerViewSet):
    model = models.Gruppi

    serializers = {
        'list':    serializers.ListaGruppi,
        'detail':  serializers.DettaglioGruppi,
        # etc.
    }

7 个答案:

答案 0 :(得分:225)

覆盖您的get_serializer_class方法。在模型mixins中使用此方法来检索正确的Serializer类。

请注意,还有一个get_serializer方法可以返回正确的序列化程序的实例

class DualSerializerViewSet(viewsets.ModelViewSet):
    def get_serializer_class(self):
        if self.action == 'list':
            return serializers.ListaGruppi
        if self.action == 'retrieve':
            return serializers.DettaglioGruppi
        return serializers.Default # I dont' know what you want for create/destroy/update.                

答案 1 :(得分:69)

你可能会发现这个mixin很有用,它会覆盖get_serializer_class方法,并允许你声明一个dict,它将action和serializer类或者fallback映射到通常的行为。

class MultiSerializerViewSetMixin(object):
    def get_serializer_class(self):
        """
        Look for serializer class in self.serializer_action_classes, which
        should be a dict mapping action name (key) to serializer class (value),
        i.e.:

        class MyViewSet(MultiSerializerViewSetMixin, ViewSet):
            serializer_class = MyDefaultSerializer
            serializer_action_classes = {
               'list': MyListSerializer,
               'my_action': MyActionSerializer,
            }

            @action
            def my_action:
                ...

        If there's no entry for that action then just fallback to the regular
        get_serializer_class lookup: self.serializer_class, DefaultSerializer.

        """
        try:
            return self.serializer_action_classes[self.action]
        except (KeyError, AttributeError):
            return super(MultiSerializerViewSetMixin, self).get_serializer_class()

答案 2 :(得分:7)

此答案与接受的答案相同,但我更喜欢这样做。

Generic views

  

get_serializer_class(self):

     

返回应用于序列化程序的类。默认为返回serializer_class属性。

     

可以重写以提供动态行为,例如使用不同的序列化器进行读写操作,或为不同类型的用户提供不同的序列化器。   serializer_class属性。

class DualSerializerViewSet(viewsets.ModelViewSet):
    # mapping serializer into the action
    serializer_classes = {
        'list': serializers.ListaGruppi,
        'retrieve': serializers.DettaglioGruppi,
        # ... other actions
    }
    default_serializer_class = DefaultSerializer # Your default serializer

    def get_serializer_class(self):
        return self.serializer_classes.get(self.action, self.default_serializer_class)

答案 3 :(得分:6)

基于@gonz和@ user2734679的答案,我创建了this small python package,它在ModelViewset的子类中提供了这个功能。这是它的工作原理。

from drf_custom_viewsets.viewsets.CustomSerializerViewSet
from myapp.serializers import DefaltSerializer, CustomSerializer1, CustomSerializer2

class MyViewSet(CustomSerializerViewSet):
    serializer_class = DefaultSerializer
    custom_serializer_classes = {
        'create':  CustomSerializer1,
        'update': CustomSerializer2,
    }

答案 4 :(得分:4)

关于提供不同的序列化程序,为什么没有人选择检查HTTP方法的方法?它更清晰的IMO,不需要额外的检查。

def get_serializer_class(self):
    if self.request.method == 'POST':
        return NewRackItemSerializer
    return RackItemSerializer

致谢/来源:https://github.com/encode/django-rest-framework/issues/1563#issuecomment-42357718

答案 5 :(得分:0)

尽管似乎最明显的documented方式预定义了多个序列化器,但FWIW有另一种方法可以利用其他文档代码,并可以在将参数传递给序列化器时使用被实例化。我认为,如果您需要根据各种因素(例如用户管理员级别,所调用的操作甚至可能是实例的属性)生成逻辑,那可能会更有价值。

第一个难题是dynamically modifying a serializer at the point of instantiation上的文档。该文档没有说明如何从视图集中调用此代码,也没有说明如何在初始化字段后修改字段的只读状态-但这并不难。

第二部分-get_serializer method也被记录了-(在“其他方法”下,距get_serializer_class的页面稍远处),因此应该可以安全地依赖(并且源很简单,希望能减少因修饰而引起的意外副作用的机会)。检查GenericAPIView下的源代码(ModelViewSet-以及所有其他似乎内置的视图集类-继承自定义了get_serializer的GenericAPIView。

将两者放在一起,您可以执行以下操作:

在序列化器文件中(对我来说base_serializers.py):

class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
"""

def __init__(self, *args, **kwargs):
    # Don't pass the 'fields' arg up to the superclass
    fields = kwargs.pop('fields', None)

    # Adding this next line to the documented example
    read_only_fields = kwargs.pop('read_only_fields', None)

    # Instantiate the superclass normally
    super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

    if fields is not None:
        # Drop any fields that are not specified in the `fields` argument.
        allowed = set(fields)
        existing = set(self.fields)
        for field_name in existing - allowed:
            self.fields.pop(field_name)

    # another bit we're adding to documented example, to take care of readonly fields 
    if read_only_fields is not None:
        for f in read_only_fields:
            try:
                self.fields[f].read_only = True
            exceptKeyError:
                #not in fields anyway
                pass

然后,您可以在视图集中执行以下操作:

class MyViewSet(viewsets.ModelViewSet):
    # ...permissions and all that stuff

    def get_serializer(self, *args, **kwargs):

        # the next line is taken from the source
        kwargs['context'] = self.get_serializer_context()

        # ... then whatever logic you want for this class e.g:
        if self.action == "list":
            rofs = ('field_a', 'field_b')
            fs = ('field_a', 'field_c')
        if self.action == “retrieve”:
            rofs = ('field_a', 'field_c’, ‘field_d’)
            fs = ('field_a', 'field_b’)
        #  add all your further elses, elifs, drawing on info re the actions, 
        # the user, the instance, anything passed to the method to define your read only fields and fields ...
        #  and finally instantiate the specific class you want (or you could just
        # use get_serializer_class if you've defined it).  
        # Either way the class you're instantiating should inherit from your DynamicFieldsModelSerializer
        kwargs['read_only_fields'] = rofs
        kwargs['fields'] = fs
        return MyDynamicSerializer(*args, **kwargs)

就应该这样!现在,使用MyViewSet应该使用您想要的参数实例化MyDynamicSerializer-并假设序列化程序继承自DynamicFieldsModelSerializer,它应该知道该怎么做。

也许值得一提的是,如果您想以其他一些方式来适配串行器,则它可能具有特殊意义。执行类似read_only_exceptions列表的操作,并将其用于将字段白名单而不是黑名单(我倾向于这样做)。我还发现将字段设置为空元组(如果未通过),然后删除对None的检查非常有用,然后将继承的序列化程序上的字段定义设置为“ 全部”。这意味着实例化序列化程序时没有传递的字段不会偶然幸免,而且我也不必将序列化程序调用与继承的序列化程序类定义进行比较,以了解其中包含的内容...例如,在 init < / strong>的DynamicFieldsModelSerializer:

# ....
fields = kwargs.pop('fields', ())
# ...
allowed = set(fields)
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)
# ....

NB 如果我只想将两到三个类映射到不同的操作,并且/或者我不想要任何特别动态的序列化程序行为,那么我可能会使用其他人在这里提到的一种方法,但我认为值得一提,尤其是考虑到它的其他用途。

答案 6 :(得分:0)

提到所有其他解决方案,我无法找到如何使用 get_serializer_class 函数实例化类,也无法找到自定义验证函数。对于那些仍然像我一样迷茫并希望完全实施的人,请查看下面的答案。

views.py

from rest_framework.response import Response

from project.models import Project
from project.serializers import ProjectCreateSerializer, ProjectIDGeneratorSerializer


class ProjectViewSet(viewsets.ModelViewSet):
    action_serializers = {
        'generate_id': ProjectIDGeneratorSerializer,
        'create': ProjectCreateSerializer,
    }
    permission_classes = [IsAuthenticated]

    def get_serializer_class(self):
        if hasattr(self, 'action_serializers'):
            return self.action_serializers.get(self.action, self.serializer_class)

        return super(ProjectViewSet, self).get_serializer_class()

    # You can create custom function
    def generate_id(self, request):
        serializer = self.get_serializer_class()(data=request.GET)
        serializer.context['user'] = request.user
        serializer.is_valid(raise_exception=True)
        return Response(serializer.validated_data, status=status.HTTP_200_OK)

    def create(self, request, **kwargs):
        serializer = self.get_serializer_class()(data=request.data)
        serializer.context['user'] = request.user
        serializer.is_valid(raise_exception=True)
        return Response(serializer.validated_data, status=status.HTTP_200_OK)

serializers.py

import random
from rest_framework import serializers
from project.models import Project


class ProjectIDGeneratorSerializer(serializers.Serializer):
    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        pass

    projectName = serializers.CharField(write_only=True)

    class Meta:
        fields = ['projectName']

    def validate(self, attrs):
        project_name = attrs.get('projectName')
        project_id = project_name.replace(' ', '-')

        return {'projectID': project_id}


class ProjectCreateSerializer(serializers.Serializer):
    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        pass

    projectName = serializers.CharField(write_only=True)
    projectID = serializers.CharField(write_only=True)

    class Meta:
        model = Project
        fields = ['projectName', 'projectID']

    def to_representation(self, instance: Project):
        data = dict()
        data['projectName'] = instance.name
        data['projectID'] = instance.projectID
        data['createdAt'] = instance.createdAt
        data['updatedAt'] = instance.updatedAt

        representation = {
            'message': f'Project {instance.name} has been created.',
        }

        return representation

    def validate(self, attrs):
        print('attrs', dict(attrs))
        project_name = attrs.get('projectName')
        project_id = attrs.get('projectID')

        if Project.objects.filter(projectID=project_id).first():
            raise serializers.ValidationError(f'Project with ID {project_id} already exist')

        project = Project.objects.create(projectID=project_id,
                                         name=project_name)

        print('user', self.context['user'])
        project.user.add(self.context["user"])

        project.save()

        return self.to_representation(project)

urls.py

from django.urls import path

from .views import ProjectViewSet

urlpatterns = [
    path('project/generateID', ProjectViewSet.as_view({'get': 'generate_id'})),
    path('project/create', ProjectViewSet.as_view({'post': 'create'})),
]

models.py

# Create your models here.
from django.db import models

from authentication.models import User


class Project(models.Model):
    id = models.AutoField(primary_key=True)
    projectID = models.CharField(max_length=255, blank=False, db_index=True, null=False)
    user = models.ManyToManyField(User)
    name = models.CharField(max_length=255, blank=False)
    createdAt = models.DateTimeField(auto_now_add=True)
    updatedAt = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name