drf-nested-routers
drf-nested-routers copied to clipboard
Document ModelSerializer.create method
In the documentation is no mention how to use ModelSerializer
for the simple NameserverViewSet
, so that the POST method would work and associate the domain_pk
field.
I don't know how to use it correctly, but I came up with this (after some time of experimenting):
from rest_framework import serializers
from .models import Nameserver
class NameserverSerializer(serializers.ModelSerializer):
class Meta:
model = Nameserver
fields = [
...
]
def create(self, validated_data):
validated_data['domain_id'] = self.context['view'].kwargs['domain_pk']
return super().create(validated_data)
Another way to do it in the ViewSet I found here https://github.com/alanjds/drf-nested-routers/issues/187#issuecomment-684039173
class NameserverViewset(viewsets.ModelViewSet):
(...)
def perform_create(self, serializer):
serializer.save(user=self.request.user, domain_id=self.kwargs['domain_pk'])