当太多的子关系时,可浏览的API变得不可读

时间:2018-01-18 08:23:01

标签: python django django-rest-framework

如何限制HyperlinkedModelSerializer的HyperlinkedRelatedField中列出的子关系数?当有hundreads或数以千计的子关系时,整个页面变得非常快速且不可读且速度慢。页面大小本身不是问题,但可以看到多少个子关系。

class FooSerializer(serializers.HyperlinkedModelSerializer):
    bars = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='bar-detail')

    class Meta:
        model = Foo
        fields = '__all__'

class Bar(models.Model):
    name = models.CharField(max_length=200)
    foo = models.ForeignKey(Foo, related_name="bars", on_delete=models.PROTECT)

在可浏览的API中:/ api / v1 / foos /

{
    "count": 6,
    "next": null,
    "previous": null,
    "results": [
        {
            "url": "http://localhost:8000/api/v1/foos/1/",
            "name": "Something"
            "bars": [
                "http://localhost:8000/api/v1/bars/3/",
                "http://localhost:8000/api/v1/bars/4/",
                "http://localhost:8000/api/v1/bars/5/",
                "http://localhost:8000/api/v1/bars/6/",
                "http://localhost:8000/api/v1/bars/7/",
                "http://localhost:8000/api/v1/bars/8/",
                "http://localhost:8000/api/v1/bars/9/",
                "http://localhost:8000/api/v1/bars/10/",
                "http://localhost:8000/api/v1/bars/11/",
                "http://localhost:8000/api/v1/bars/12/",
                "http://localhost:8000/api/v1/bars/13/",
                .....

正如您所看到的,此列表变得非常快。最好把它削减到最多五个左右。 对于Form输入字段有HTML_SELECT_CUTOFF,但我相信没有类似于read_only = True字段?

1 个答案:

答案 0 :(得分:1)

尝试以下操作:不使用直接关系,而是使用属性只获取部分子项:

class Foo(models.Model):
    # ...
    @property    
    def bars_top(self):
        items_to_show = 5
        return self.bars.all()[:items_to_show]


class FooSerializer(serializers.HyperlinkedModelSerializer):
    bars_top = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='bar-detail')

    class Meta:
        model = Foo
        fields = ('id', 'bars_top')