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

2024-04-20 08:27:44 发布

您现在位置:Python中文网/ 问答频道 /正文

如何限制HyperlinkedModelSerializer的HyperlinkedLatedField中列出的子关系数?当有成百上千的子关系时,整个页面很快就变得不可读和缓慢。页面大小本身不是问题,而是有多少子关系是可见的。你知道吗

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/",
                .....

如你所见,这个列表很快就会变得很长。最好把它剪到最多五个左右。 对于表单输入字段,有HTML\u SELECT\u CUTOFF,但我相信没有什么类似于read\u only=True字段?你知道吗


Tags: nameapitruelocalhosthttponlyread关系
1条回答
网友
1楼 · 发布于 2024-04-20 08:27:44

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

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')

相关问题 更多 >