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 Rating
s, 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
- [Answered ]-Why do I get a '403 (Forbidden)' error with Dajaxice?
- [Answered ]-Django how to override 'get_or_create' to create parent object if it doesn't exist
- [Answered ]-How to retrieve the field which triggered a hit for a elasticsearch query
Source:stackexchange.com