方法一:
n = 10
i = random.randint(0, Article.objects.count()-n)
articles = Article.objects.all()[i:i+n]
通過(guò)Article.objects.count()得到所有數(shù)據(jù)條數(shù),通random函數(shù)得到其中一個(gè)數(shù)據(jù),然后再在這條數(shù)據(jù)的位置選擇10條數(shù)據(jù),此方法不是真正的隨機(jī)取數(shù)據(jù)。
方法二:
count = Article.objects.all().count()
rand_ids = sample(range(1, count), 10)
print(rand_ids)
articles = Article.objects.filter(id__in=rand_ids)
同上計(jì)算所有數(shù)據(jù)條數(shù),通過(guò)sample方法得到10條數(shù)據(jù),通過(guò)filter的方法,查找id__in在這個(gè)數(shù)據(jù)位的值。
方法三:
import random
content_pks = Article.objects.values_list('pk', flat=True)
selected_pks = random.sample(list(content_pks), 3)
content_objects = Article.objects.filter(pk__in=selected_pks)
print(content_objects)
方法四:
total_count= Content.objects.count()
fraction = 100./total_count
object_list = [ c for c in Content.objects.all() if random.random() < fraction ]