99lives 99lives - 7 months ago 99
Python Question

Django REST Framework nested serializer having no effect

I am attempting to set up a nested serializer in Django REST Framework, but after following the short guide in the documentation, http://www.django-rest-framework.org/api-guide/relations/#nested-relationships, I have had no change in the serialized data.

models.py

class Franchise(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)


class Item(models.Model):
id = models.AutoField(primary_key=True)
franchise = models.ForeignKey(Franchise, on_delete=None)
title = models.CharField(max_length=255)


Initial serializers.py

class ItemListSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('id', 'franchise', 'title')


class FranshiseDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Franchise
fields = ('id', 'name', 'items')


When I query
ItemListSerializer
with a query set I get back the expected:

[
{
"id": 1,
"franchise": 1,
"title": "Item 1",
},
{
"id": 2,
"franchise": 1,
"title": "Item 2"
},
{
"id": 3,
"franchise": 2,
"title": "Item 3",
}
]


And the expected result when I query
FranchiseDetailSerializer
with a pre-existing franchise object.

{
"id": 1,
"name": "Franchise 1"
}


Now, when I change
FranchiseDetailSerializer
, as per the DRF guide on nested relations:

class FranshiseDetailSerializer(serializers.ModelSerializer):
items = ItemListSerializer(many=True, read_only=True)

class Meta:
model = Franchise
fields = ('id', 'name', 'items')


I would expect the get the following result:

{
"id": 1,
"name": "Franchise 1"
"items": [
{"id": 1, "title": "Item 1", "franchise": 1},
{"id": 2, "title": "Item 2", "franchise": 1}
]
}


But instead, I get no change, as though I hadn't updated
FranchiseDetailSerializer
at all:

{
"id": 1,
"name": "Franchise 1"
}


The worst part about this for me is that I am not getting any kind of error, I'm simply not seeing results.

Any and all help is appreciated, thanks.

Answer

Actually you missed a tiny part of docs :)

album = models.ForeignKey(Album, related_name='tracks')

Define related_name in ForeignKey

franchise = models.ForeignKey(Franchise, on_delete=None, related_name='items')

After that stuff started working for me.

Comments