[PYTHON] Sometimes you want to access View information from Serializer with DRF (Django REST Framework)

Regardless of whether this is good or not, there are times when you want to access View information from Serializer. We use a convenient Mixin that can be used in such cases internally. The more you do, the stronger the bond between View and Serializer, so we recommend that you follow the usage and dosage __.

Anyway, it's the source code.

ViewAccessSerializerMixin

class ViewAccessSerializerMixin(object):

    def get_view_action(self):
        """
Access View action from Serializer
        """
        context = getattr(self, 'context')
        if not context:
            warnings.warn('The context does not exist in the serializer. The instance is created in an illegal way')
            return None
        return context.get('view').action

    def get_view_kw(self, key, default=None):
        """
Access view kwargs from Serializer
        """
        context = getattr(self, 'context')
        if not context:
            warnings.warn('The context does not exist in the serializer. The instance is created in an illegal way')
            return default
        return context.get('view').kwargs.get(key, default)

    def get_kwargs_object(self, key, model_class):
        """
Access kwargs from the Serializer, treat it as an id, and search for the specified model
        """
        obj = model_class.objects.get_or_none(id=int(self.get_view_kw(key, 0)))
        if obj:
            return obj

Access the view action

Mostly used in validation. I think there are probably better conditions. Like this.

class HogeSerializer(ViewAccessSerializerMixin, serializers.ModelSerializer):

    #Various omissions

    def validate(self, attrs):
        #Change the verification content depending on the action
        action_name = self.get_view_action()
        if action_name == "xxxx":
            pass
        else:
            pass

Access kwargs in View

Mostly used in SerializerMethodField.

class PostHistorySerializer(ViewAccessSerializerMixin, serializers.ModelSerializer):

    #Various omissions

    comments = serializers.SerializerMethodField()

    def get_comments(self, obj):
        return obj.comment.filter(user_id=self.get_view_kw("user_pk"))

Access kwargs in View, consider it an id, and search for the specified model

It's close to the combination of ↑, but it's a shortcut.

class UserSerializer(ViewAccessSerializerMixin, serializers.ModelSerializer):

    #Various omissions

    def validate(self, attrs):
        user = self.get_kwargs_object('user_pk', models.User)
        if user.is_ban():
          raise NotFound()
        pass

Basically, I use it like this. I hope you can use it conveniently.

Recommended Posts

Sometimes you want to access View information from Serializer with DRF (Django REST Framework)
When you want to filter with Django REST framework
How to automatically generate API document with Django REST framework & POST from document screen
Django REST framework with Vue.js
Login with django rest framework
[Django] Use MessagePack with Django REST framework
Create a REST API to operate dynamodb with the Django REST Framework
How to deal with garbled characters in json of Django REST Framework
Create RESTful APIs with Django Rest Framework
CRUD GET with Nuxt & Django REST Framework ②
CRUD POST with Nuxt & Django REST Framework
CRUD GET with Nuxt & Django REST Framework ①
AssertNumQueries is useful if you want to easily test N + 1 queries with django
If you want to make a discord bot with python, let's use a framework
CRUD PUT, DELETE with Nuxt & Django REST Framework
Pass login user information to view in Django
Django REST framework A little useful to know.
Implementing authentication in Django REST Framework with djoser
Create a Todo app with Django REST Framework + Angular
More new user authentication methods with Django REST Framework
Settings when you want to run python-mecab with travis
Create a Todo app with the Django REST framework
Create APIs around user authentication with Django REST Framework
Links to do what you want with Sublime Text
Passing confidential information from SSM to ECS with CloudFormation
Allows you to select by name from Django User Name
Things to do when you start developing with Django
Implement hierarchical URLs with drf-nested-routers in Django REST framework
ODBC access to SQL Server from Linux with Python