Django-rest-framework, nested objects in Serializers

I would like to have a nested object inside the serializer, not just foreignkey (or url). As in this documentation , I just needed to specify the serializer class of the nested object in the parent serializer:

# Models class NestedSample(models.Model): something = models.CharField(max_length=255) class Sample(models.Model): thing = models.BooleanField() nested = models.ForeignKey(NestedSample) # Serializers class NestedSampleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = api_models.NestedSample class SampleSerializer(serializers.HyperlinkedModelSerializer): nested = NestedSampleSerializer() # HERE! class Meta: model = api_models.Sample # Views class NestedSampleViewSet(viewsets.ModelViewSet): queryset = api_models.NestedSample.objects.all() serializer_class = api_serializers.NestedSampleSerializer class SampleViewSet(viewsets.ModelViewSet): queryset = api_models.Sample.objects.all() serializer_class = api_serializers.SampleSerializer 

This works very well when I receive objects, but it is no longer possible to create (= POST ) Sample objects, I get an error:

 {u'non_field_errors': [u'Invalid data']} 

I tried to overwrite the create method in the view to get the object using pk:

 class SampleViewSet(viewsets.ModelViewSet): queryset = api_models.Sample.objects.all() serializer_class = api_serializers.SampleSerializer def create(self, request): request.DATA['nested'] = get_object_or_404(api_models.NestedSample, pk=request.DATA['nested']) return super(SampleViewSet, self).create(request) 

But that does not work.

Any idea?

I also found this question . I can relate this to the fact that, of course, solves the problem, but do not let me expose the full nested object, so let's return to the beginning.

Thanks,

+7
serialization django-rest-framework nested
source share
2 answers

I can imagine two solutions to this problem. I prefer the first one.

First decision:

Use the django model form to create objects. Override the create and update methods. Sample creation method:

 def create(self, request): form = SampleForm(data=request.POST) if form.is_valid(): instance = form.save(commit=False) instance.save() return Response(dict(id=instance.pk), status=status.HTTP_201_CREATED) return Response(form.errors, status=status.HTTP_400_BAD_REQUEST) 

This way you can create Sample objects with any necessary validation.

The second solution:

Override the get_serializer_class method and return the serializer class based on the request method. Define two serializers, one for the message and put, and the other for the list and extract.

+2
source share

Can you confirm that you are sending a JSON-encoded request, i.e. the request has a content type set to JSON? If not, the message is most likely sent using a form format that does not support nested ones.

+2
source share

All Articles