I have a "Category" model which has a foreign key pointing to itself. The idea is that categories can have sub-categories. As far as the normal django ORM is concerned this works great, but I think I'm having trouble serializing categories. My aim is to have a serialization like:
{
"name": "Category 1",
"subcategories": [
{
"name": "Category 1A (a sub-category)",
"subcategories": [...]
},
]
}
And of course it would be nice to have a limit on how deep the structure goes, but I haven't been able to get that far because I'm running up against an issue where the nesting doesn't seem to serialize right:
# ListAPIView output for serializer below:
{
"created": "2013-02-18T01:09:48Z",
"name": "category number 1",
"subcategories": [
"Category object"
]
},
Anyone have any ideas on the right way to do this? Custom relational field?
Cheers
# --- Model ----
class Category(Model):
created = models.DateTimeField()
name = models.CharField(max_length=255)
parent = models.ForeignKey("self", blank=True, null=True, related_name="subcategories")
# (a self-referenced foreign key)
# ---- Serializer ----
class CategorySerializer(serializers.ModelSerializer):
subcategories = serializers.RelatedField(many=True, read_only=True)
class Meta:
model = Suite
fields = ('created', 'name', 'subcategories')