Reputation:
I have two SerializerMethodFields on a serializer. One of them returns obj.somelist.count() fine. But where I am asking the other method to return obj.somelist[0] I'm getting a TypeError 'RelatedManager' object does not support indexing. Any advice is much appreciated. Here's some code:
class TripPlaceSerializer(serializers.ModelSerializer):
class Meta:
model = TripPlace
fields = ('trip', 'place', )
class StopSerializer(serializers.ModelSerializer):
class Meta:
model = TripPlace
fields = ('place', )
depth = 1
class TripSerializer(serializers.ModelSerializer):
stops = StopSerializer(read_only=True, many=True)
stops_count = serializers.SerializerMethodField()
car = CarSerializer(read_only=True, many=False)
origin = serializers.SerializerMethodField()
# final = serializers.SerializerMethodField()
class Meta:
model = Trip
fields = ('id', 'name', 'owner', 'car', 'stops_count', 'stops', 'origin', )
def get_stops_count(self, obj):
return obj.stops.count()
def get_origin(self, obj):
return obj.stops.first()
Upvotes: 2
Views: 2553
Reputation: 78556
obj.somelist
is the RelatedManager
for whatever the underlying relationship is, you can't index it directly. You should call the first
method of the RelatedManager
to get the first object:
def get_origin(self, obj):
return obj.somelist.first()
Or you can index(or slice) a queryset of the manager using a different index different from 0
:
def get_origin(self, obj):
return obj.somelist.all()[ind]
Upvotes: 5