Django Rest Framework限制从多个序列化器中拉出的项目数量

时间:2017-01-11 16:26:23

标签: django django-rest-framework

这是我的模特:

class Campaign(models.Model):
    ...
    associated_entities = models.ManyToManyField(db_index=True, to='Entity', through='EntityToCampaignMap')
    ...

广告系列可以包含许多实体,但我想在此限制我使用序列化程序提取的实体数量:

class CampaignSerializer(serializers.ModelSerializer):
    ...
    associated_entities = EntityToCampaignMapSerializer(source='entitytocampaignmap_set', many=True)

    class Meta:
        model = Campaign
        fields = (
        'id', ... 'associated_entities', ...)

这可以吸引尽可能多的实体。有没有办法限制它说,最多50个元素?

为了澄清,我不打算对已经处理过的Campaign模型进行分页。我试图限制从多对多关系拉出的实体数量

我也在使用自定义映射,所以我需要使用这个序列化器:

class EntityToCampaignMapSerializer(serializers.ModelSerializer):
    entity = EntitySerializer()
    relationship = serializers.SlugRelatedField(slug_field='relationship_label', read_only=True)

    class Meta:
        model = EntityToCampaignMap
        fields = ('entity', 'relationship')

1 个答案:

答案 0 :(得分:1)

您需要的是不同的source

class CampaignSerializer(serializers.ModelSerializer):
    ...
    associated_entities = SerializerMethodField('get_limited_number_of_whatever')
    ...

    def get_limited_number_of_whatever(self, obj):
          qs = obj.entitytocampaignmap_set.all()
          if not self.context['verbose']:
               # In case you don't want ALL E2C instances, limit the queryset
               qs = qs[:50]
          return EntityToCampaignMapSerializer(instance=qs, many=True).data