1.选择2.过滤器3.然后切割



我正在尝试执行以下逻辑:

1. take all objects
2. filter them: all objs which has rate value >= 4
3. then take randomly 4 out of them. 

如何从中随机抽取4个?不仅仅是从末端切割

这是我的代码:
MyObj.objects.filter(objects__rate__gte=4).distinct('id').order_by('-id')[:4]

也许您可以使用:

random.sample(population, k)

返回从population序列中选择的唯一元素的k长度列表。用于无需更换的随机采样

http://docs.python.org/2/library/random.html#random.sample

Django可以选择随机订购。这是通过使用.order_by('?')来完成的。

所以你的代码是:

MyObj.objects.filter(rate__gte=4).distinct('id').order_by('?')[:4]

它实际上在django文档中有说明,可以在此处查看https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-通过

foo = MyObj.objects.filter(objects__rate__gte=4) # step 1 & 2
random.sample(list(foo), 4) # step 3 (will contain duplicates)
random.sample(set(foo), 4) # step 3, only uniques

相关内容

最新更新