How to get 2 level nested related field in serializer?

1,237 views
Skip to first unread message

Jon Tart

unread,
Dec 17, 2014, 1:09:00 PM12/17/14
to django-res...@googlegroups.com
I have 3 models:

class City(models.Model):
    name
= models.CharField()


class Place(models.Model):
    city
= models.ForeignKey(City)


class Submission(models.Model):
    place
= models.ForeignKey(Place)
    comment
= models.CharField()



I have a serializer like this:

class SubmissionSerializer(serializers.ModelSerializer):
   
class Meta:
        model
= Submission
        fields
= ('id', 'place__city_name', 'comment')
        read_only_fields
= ('id', 'place__city_name')


But I'm getting ImproperlyConfigured exception:

Field name `place__city_name` is not valid for model `ModelBase`.

What am I doing wrong? I basically want to display city name of the submission which is behind 2 foreign keys. How can I achieve this?

Thanks in advance!

Xavier Ordoquy

unread,
Dec 17, 2014, 1:16:10 PM12/17/14
to django-res...@googlegroups.com
Hi Jon,

You are looking for nested serializers.
The documentation has a few words about it there: http://www.django-rest-framework.org/api-guide/relations/#nested-relationships and within the 3.0 announcement you also have a section called "Writable nested serialization » (http://www.django-rest-framework.org/topics/3.0-announcement/).

Regards,
Xavier Ordoquy,
Linovia.

Reply all
Reply to author
Forward
0 new messages