django-rest-framework, multitable model inheritance, ModelSerializers and nested serializers

后端 未结 4 2106
小蘑菇
小蘑菇 2020-12-29 07:01

I can\'t find this info in the docs or on the interwebs.
latest django-rest-framework, django 1.6.5

How does one create a ModelSerializer that can handle a nes

4条回答
  •  清歌不尽
    2020-12-29 07:12

    Using Django 3.1, I found that it is possible to override get_serializer instead of get_serializer_class, in which case you can access the instance as well as self.action and more.

    By default get_serializer will call get_serializer_class, but this behavior can be adjusted to your needs.

    This is cleaner and easier than the solutions proposed above, so I'm adding it to the thread.

    Example:

    class MySubclassViewSet(viewsets.ModelViewSet):
        # add your normal fields and methods ...
    
        def get_serializer(self, *args, **kwargs):
            if self.action in ('list', 'destroy'):
                return MyListSerializer(args[0], **kwargs)
            if self.action in ('retrieve', ):
                instance = args[0]
                if instance.name.contains("really?"):  # or check if instance of a certain Model...
                    return MyReallyCoolSerializer(instance)
                else return MyNotCoolSerializer(instance)
            # ... 
            return MyListSerializer(*args, **kwargs)  # default
    

提交回复
热议问题