[Answered ]-AttributeError: 'MovieSerializer' object has no attribute 'id' + Serialization

1๐Ÿ‘

โœ…

You should filter on the .id of the obj, not of self, since self is the serializer, not the object the serializer is working on:

def get_rating(self, obj):
    r = Rating.objects.filter(movie_id=obj.id).values()[0]
    r['rating'] = float(r['rating'])
    return r

It is however likely better to work with a RatingSerializer. You can not use the RatingSerializer at the bottom, since that would result in an infinite recursion: serializing the movie would serialize all the related ratings with the corresponding movies with the corresponding ratings, etc.

We thus can make a simple (flat) serializer for the Ratings, and work with:

class SimpleRatingSerializer(serializers.ModelSerializer):
    class Meta:
        model = Rating
        # no movie
        fields = ['id', 'rating', 'votes']

class MovieSerializer(serializers.ModelSerializer):
    director = PersonSerializer()
    rating = SimpleRatingSerializer(many=True)
    
    class Meta:
        model = Movie
        fields = ['id', 'title', 'director', 'rating']

0๐Ÿ‘

Eventually this works fine.

class MovieSerializer(serializers.ModelSerializer):
    director = PersonSerializer()
    rating = serializers.SerializerMethodField()
    votes = serializers.SerializerMethodField()
    
    def get_rating(self, obj):
        r = list(Rating.objects.filter(movie_id=obj.id).values())[0]
        return json.dumps(float(r['rating']))

    def get_votes(self, obj):
        r = list(Rating.objects.filter(movie_id=obj.id).values())[0]
        return json.dumps(r['votes'])

    class Meta:
        model = Movie
        fields = ['id', 'title', 'director', 'rating', 'votes']

๐Ÿ‘คkakakakakakakk

Leave a comment