-
Notifications
You must be signed in to change notification settings - Fork 157
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
Creating nested object #187
Comments
Yes, but you will need custom code to do it. On some project, I am using code alike this one: class NameserverViewset(viewsets.ModelViewSet):
(...)
def initialize_request(self, request, *args, **kwargs):
request = super().initialize_request(request, *args, **kwargs)
for querydict in [request.data, request.query_params]:
initial_mutability = getattr(querydict, '_mutable', None)
if initial_mutability is not None:
querydict._mutable = True
querydict['domain'] = kwargs['domain_pk']
if initial_mutability is not None:
querydict._mutable = initial_mutability
return request However is unclear for me if such code should be provided by drf-nested-routers as a custom viewset superclass or/and if it should be included on the docs. What is your opinion? |
class NameserverViewset(viewsets.ModelViewSet):
(...)
def perform_create(self, serializer):
serializer.save(user=self.request.user, domain_id=self.kwargs['domain_pk']) is what I was looking for 😛 thanks. |
I'd say mentioning how to get the parent pk is good enough. This looks hacky and breakable. |
Could someone kindly post a complete solution to this with their Serializer and ViewSet please? I am not seeing this work at all. For me the Here is my Serializer and ViewSet:
So it seems that first the serializer validation must pass before |
I guess you need to set required=False for the domain field in your serializer. The error would be in creating a serializer object if you go through the stack trace. |
Ok I see. Another solution which I've opted for is to just remove the field from the list, since the value is not POSTed I guess this makes sense anyways. Here is the solution for anyone else:
I was originally under the impression that I would get validation of the
This appears not to be the case. Might be worth mentioning some of this in the docs. |
Since this is somewhat related, is there a recommended way to perform validation of the parent primary key in the URL? With the above solution, making a POST to say Where would it be best to handle this Exception? |
Is there a way I can create a nested object without passing the ID of the parent?
e.g
The text was updated successfully, but these errors were encountered: