如何在DRF序列化器的GenericRelation字段中返回链接对象的计数?

时间:2019-05-25 20:57:08

标签: django-rest-framework

在Django Rest Framework中,有许多关于serializing GenericRelations的问题,但是我有一个用例,我只想只返回GenericRelation字段中的对象计数而不序列化它们。我可以找到的文档和现有问题不涵盖此内容。

我认为这可能与在自定义序列化程序中返回len(value)一样简单,但是会产生以下错误:

object of type 'GenericRelatedObjectManager' has no len()

我的尝试失败:

class ObjectCountSerializer(serializers.RelatedField):
    """
    Return the count of related objects.
    """

    def to_representation(self, value):
        return len(value)

class PostListSerializer(serializers.ModelSerializer):
    """
    Main serializers for the writings module
    """
    author = MemberListSerializer(many=False, read_only=True)
    comments = ObjectCountSerializer(read_only=True)

    class Meta:
        model = Post
        fields = (
            'id',
            'slug',
            'url',
            'title',
            'description',
            'created',
            'edited',
            'author',
            'comments'
        )
        lookup_field = 'slug'
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

如何简单地返回关系中的对象数?

1 个答案:

答案 0 :(得分:1)

我想说SerializerMethodField可以解决这个问题,例如

class PostListSerializer(serializers.ModelSerializer):
    """
    Main serializers for the writings module
    """
    author = MemberListSerializer(many=False, read_only=True)
    comments = serializers.SerializerMethodField()

    def get_comments(self, instance):
        return instance.comments.count()

    class Meta:
        model = Post
        fields = (
            'id',
            'slug',
            'url',
            'title',
            'description',
            'created',
            'edited',
            'author',
            'comments'
        )
        lookup_field = 'slug'
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

SerializerMethodField是一个只读字段,它返回方法的结果,通常命名为get_<field_name>