There are two models with one-to-many connectivity, just like docks

class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() genre = models.CharField(max_length=50, choices=GENRE) title = models.CharField(max_length=100) duration = models.IntegerField() class Meta: unique_together = ('album', 'order') ordering = ['order'] def __unicode__(self): return '%d: %s' % (self.order, self.title) 

django-rest-framework allows you to consider this connection

 class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('order', 'title', 'duration') class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') 

and create nested structures with which you can work both for reading and writing

 { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ... ], } 

Is it possible to create structures with additional nesting, for example, to take into account the division by genre field?

 { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ { 'rock': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}], 'classic': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}] ... } ], } 

I know that I can use SerializerMethodField () for properties and get any structure, but this method creates only read-only fields with no possibility of change.

What other ways is there to solve the problem?

  • one
    Write your serializer in which to manually collect and parse the data. See how the ModelSerializer class is implemented and how it differs from the Serializer class. Then create your class, inherited from Serailizer. - Chikiro
  • Yes, I am already rewriting api with a custom serializer, modelserializer too "inflexible" - while1pass

0