python - Django REST Framework nested serializer having no effect -
i attempting set nested serializer in django rest framework, after following short guide in documentation, http://www.django-rest-framework.org/api-guide/relations/#nested-relationships, have had no change in 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 query itemlistserializer
query set expected:
[ { "id": 1, "franchise": 1, "title": "item 1", }, { "id": 2, "franchise": 1, "title": "item 2" }, { "id": 3, "franchise": 2, "title": "item 3", } ]
and expected result when query franchisedetailserializer
pre-existing franchise object.
{ "id": 1, "name": "franchise 1" }
now, when change franchisedetailserializer
, per 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 expect following result:
{ "id": 1, "name": "franchise 1" "items": [ {"id": 1, "title": "item 1", "franchise": 1}, {"id": 2, "title": "item 2", "franchise": 1} ] }
but instead, no change, though hadn't updated franchisedetailserializer
@ all:
{ "id": 1, "name": "franchise 1" }
the worst part me not getting kind of error, i'm not seeing results.
any , appreciated, thanks.
actually missed 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 stuff started working me.
Comments
Post a Comment