favorite
<http://stackoverflow.com/questions/39898978/methodfield-containing-serialized-object-does-not-return-proper-objects-methodf#>
I have two serializers like this.
class CourseSerializer(serializers.ModelSerializer):
pk = serializers.IntegerField(read_only=True)
name = serializers.CharField(required=True, max_length=30,
allow_blank=False)
chapters = serializers.SerializerMethodField()
def get_chapters(self, obj):
queryset = Chapter.objects.all().filter(course=obj.pk)
serializer_class = ChapterSerializer(queryset, many=True)
return serializer_class.data
class ChapterSerializer(serializers.ModelSerializer):
pk = serializers.IntegerField(read_only=True)
name = serializers.CharField(required=True, max_length=30,
allow_blank=False)
course = serializers.StringRelatedField()
cards_count = serializers.SerializerMethodField()
cards_learned_count = serializers.SerializerMethodField()
cards_still_to_go = serializers.SerializerMethodField()
cards_not_learned = serializers.SerializerMethodField()
def get_cards_learned_count(self, obj):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
queryset = Card.objects.all().filter(chapter=obj.pk)
card_count = 0
for q in queryset:
card_detail = UserCardDetail.objects.all().filter(card=q,
user=user, learned=True)
card_detail.count()
card_count += card_detail.count()
return card_count
Now when I get the course serializer instead of getting the proper values
in the chapter field, I get zeroes, but when I call the chapter serializer
I get the right values.
I noticed that the MethodField works with obj - however shouldn't that be
passed already?
Is there something extra I have to pass to the chapters field?
--
You received this message because you are subscribed to the Google Groups
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.