Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-serializer

How to deserialize nested django object


I'm not really sure how I'm able to access the data of a nested serializer, with a one-to-many relation.

Here's my models:

class Album(models.Model):
    id = models.CharField(max_length=255, null=True, blank=True)
    name = models.CharField(max_length=255, null=True, blank=True)

class Title(models.Model):
    name = models.CharField(max_length=255, null=True, blank=True)
    album = models.ForeignKey(
        Album,
        related_name='titles'
    )

then I have 2 serializers:

class AlbumSerializer(serializers.ModelSerializer):
    titles = TitleSerializer(many=True)

    class Meta:
        model = Album
        fields = ['id', 'name', 'titles']

    def create(self, validated_data):
        album = Album.objects.create(
            id=validated_data.get('id'),
            name=validated_data.get('name')
        )

        titles = validated_data.pop('titles')
        for title in titles:
            title['album'] = album
            _title = Title(**title)
            _title.save()
        return album


class TitleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Title
        fields = ['name']

To deserialize and save I run the following:

album = AlbumSerializer(data=input_json)
album.is_valid()
album.save()

my problem is now, that I'm unable to access the items. Accessing the type of album.instance.titles gets me <class 'django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager'>. How can I get the titles out of it, or what am I doing wrong that I do not get a list of Titles in there?


Solution

  • You need to call all() on a RelatedManager to execute the DB query and get the results

    album.instance.titles.all()
    

    A RelatedManager is just like a normal model manager (Model.objects) that retrieves objects filtered by the relation