我有两个这样的序列化器。
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
现在,当我获得课程序列化器而不是在章节字段中获取正确的值时,我得到零,但是当我调用章节序列化器时,我得到了正确的值。
我注意到MethodField
与obj
一起使用 - 但不应该已经通过了吗?
我还有什么额外的东西要传递给章节领域吗?
编辑:输出和预期输出 的输出
{
"name": "Example 1",
"pk": 32,
"locked": false,
"chapters": [
{
"pk": 15,
"name": "Transformatori",
"course": "Tesit",
"cards_count": 5,
"cards_learned_count": 0,
"cards_still_to_go": 0,
"cards_not_learned": 0,
"favorite_cards": 0
},
],
},
预期输出
{
"name": "Example 1",
"pk": 32,
"locked": false,
"chapters": [
{
"pk": 15,
"name": "Transformatori",
"course": "Tesit",
"cards_count": 5,
"cards_learned_count": 3,
"cards_still_to_go": 0,
"cards_not_learned": 2,
"favorite_cards": 1
},
],
},