如何从 Django 过滤器中获取完全随机的序列化数据

我有以下序列化,并打算完全随机化查询数据。

class RecommendationList(generics.ListAPIView):
    model = Obj
    serializer_class = RecommendationFilterSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['uuid',]
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):
        uuid = self.request.query_params.get('uuid')
        Obj.objects.filter(user=Obj_list[0].user)
                   .filter(Q(status=Obj.Status.PUBLISHED))
                   .filter(Q(privacy=Obj.Privacy.PUBLIC))
                   .order_by('uploaded_at').reverse()
       return Obj.objects.filter(Q(status=Obj.Status.PUBLISHED) & 
               Q(approved=True)) 
                         .filter(Q(privacy=Obj.Privacy.PUBLIC))
                         .order_by('?')

有返回两行结果的建议:

import random
last = MyModel.objects.count() - 1

index1 = random.randint(0,last)
# Here's one simple way to keep even distribution for
# index2 while still gauranteeing not to match index1.
index2 = random.randint(0,last - 1)
if index2 == index1: index2 = last

# This syntax will generate "OFFSET=indexN LIMIT=1" queries
# so each returns a single record with no extraneous data.
myobj1 = MyModel.objects.all()[index1]
myobj2 = MyModel.objects.all()[index2]

但是,表行的大小超过 10000,并且在序列化请求时可能需要访问所有 10000 项。满足这个要求和关于表 O​​RDER_BY('?') 的大小成为一个非常昂贵的操作,因此我不能使用以下内容。

对此有什么建议吗?

bobostst 回答:如何从 Django 过滤器中获取完全随机的序列化数据

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/40882.html

大家都在问