I have model that looks like this:
class Category(models.Model):
parentCategory = models.ForeignKey('self', blank=True, null=True, related_name='subcategories')
name = models.CharField(max_length=200)
description = models.CharField(max_length=500)
I managed to get flat json representation of all categories with serializer:
class CategorySerializer(serializers.HyperlinkedModelSerializer):
parentCategory = serializers.PrimaryKeyRelatedField()
subcategories = serializers.ManyRelatedField()
class Meta:
model = Category
fields = ('parentCategory', 'name', 'description', 'subcategories')
Now what I want to do is for subcategories list to have inline json representation of subcategories instead of their ids. How would I do that with django-rest-framework? I tried to find it in documentation, but it seems incomplete.
This is an adaptation from the caipirginka solution that works on drf 3.0.5 and django 2.7.4:
Note that the CategorySerializer in 6th line is called with the object and the many=True attribute.
Instead of using ManyRelatedField, use a nested serializer as your field:
If you want to deal with arbitrarily nested fields you should take a look at the customising the default fields part of the docs. You can't currently directly declare a serializer as a field on itself, but you can use these methods to override what fields are used by default.
Actually, as you've noted the above isn't quite right. This is a bit of a hack, but you might try adding the field in after the serializer is already declared.
A mechanism of declaring recursive relationships is something that needs to be added.
Edit: Note that there is now a third-party package available that specifically deals with this kind of use-case. See djangorestframework-recursive.
Another option would be to recurse in the view that serializes your model. Here's an example:
I recently had the same problem and came up with a solution that seems to work so far, even for arbitrary depth. The solution is a small modification of the one from Tom Christie:
I'm not sure it can reliably work in any situation, though...
Late to the game here, but here's my solution. Let's say I'm serializing a Blah, with multiple children also of type Blah.
Using this field I can serialize my recursively-defined objects that have many child-objects
I wrote a recursive field for DRF3.0 and packaged it for pip https://pypi.python.org/pypi/djangorestframework-recursive/
Another option that works with Django REST Framework 3.3.2: