gpt4 book ai didi

Django 休息框架 : DRYer pagination for custom actions

转载 作者:行者123 更新时间:2023-12-05 00:58:42 26 4
gpt4 key购买 nike

假设我需要设置几个类似于 objects/pastobjects/future 的 GET 端点。示例:

@action(detail=False, methods=["GET"], name="Past Objects")
def past(self, request, *args, **kwargs):
startdate = datetime.datetime.now()
some_user = UserProfile.objects.get(user__username="someuser")

queryset = self.queryset.filter(
other__attribute__profile=some_user,
creation_date__lte=startdate
).order_by("-creation_date")

page = self.paginate_queryset(queryset)

if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)

serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)

以上工作正常。但是有没有办法避免 page = ... -> serializer= ... 部分?

我已经在我的 ModelViewSet 中指定了这个:

pagination_class = CustomObjectPagination

但似乎分页仅自动应用于默认方法,如 get_queryset 而不是自定义操作。每次我指定像 past 这样的自定义操作时,我是否必须编写此样板文件?

page = self.paginate_queryset(queryset)

if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)

serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)

编辑:应该更清楚地说明我是在特别询问是否有内置方法来执行上述操作。

最佳答案

我认为我们没有任何内置功能可以对 Action 应用分页。但是,我们可以有一个简单的装饰器来做到这一点。确保您的操作在使用此装饰器时返回一个列表或 QuerySet。

from functools import wraps
from django.db.models import QuerySet

def paginate(func):

@wraps(func)
def inner(self, *args, **kwargs):
queryset = func(self, *args, **kwargs)
assert isinstance(queryset, (list, QuerySet)), "apply_pagination expects a List or a QuerySet"

page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)

serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
return inner

@paginate
@action(detail=False, methods=["GET"], name="Past Objects")
def past(self, request, *args, **kwargs):
startdate = datetime.datetime.now()
some_user = UserProfile.objects.get(user__username="someuser")

queryset = self.queryset.filter(
other__attribute__profile=some_user,
creation_date__lte=startdate
).order_by("-creation_date")

return queryset

关于Django 休息框架 : DRYer pagination for custom actions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56609145/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com