It turns out that it is possible to do so. That means that if an API client creates a resource, it can get back information about it that would otherwise need to be fetched by a separate request. A true pair of request and response serializers so that even an action like create would use one serializer for the POST request and another one for producing the response. I wanted to have different read and write serializers even for the actions themselves. So you might ask, what is the problem then? This approach works well when it is enough to have different serializers based on actions. Write_serializer_class = ProjectWriteSerializer Read_serializer_class = ProjectReadSerializer serializers import ProjectReadSerializer, ProjectWriteSerializer REVSYS has an article on using different read and write serializers that would alter the behavior in the following fashion: from rest_framework. As with just about anything, DRF has a get_serializer_class hook that can be used to provide the desired serializer dynamically. serializers import ProjectSerializerÄ«ut don't despair. The problem is that a typical implementation of ModelViewSet lets us specify just one serializer: from rest_framework. But if we want to get the most out of Django REST Framework (DRF) we might prefer to use ModelViewSets, at least at the beginning, to create endpoints faster and with less code. Of course, one can go and write completely custom APIViews and use any serializers for inputs and outputs without any problems. The problem with ModelViewSets and multiple serializers However, having different request and response (or read and write) serializers for ModelViewSets is not one of them. At first glance, it seems to support just about everything you might want in a typical HTTP API. Articles About me Different request and response serializers in Django REST FrameworkÄjango REST Framework can be a very productive framework for writing HTTP endpoints based on Django models.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |