Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document ModelSerializer.create method #222

Open
PetrDlouhy opened this issue Apr 2, 2021 · 1 comment
Open

Document ModelSerializer.create method #222

PetrDlouhy opened this issue Apr 2, 2021 · 1 comment

Comments

@PetrDlouhy
Copy link

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)
@allburov
Copy link

Another way to do it in the ViewSet I found here #187 (comment)

class NameserverViewset(viewsets.ModelViewSet):
    (...)
    def perform_create(self, serializer):
        serializer.save(user=self.request.user, domain_id=self.kwargs['domain_pk'])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants