Django隨機(jī)從數(shù)據(jù)庫(kù)中取數(shù)據(jù)

方法一:

    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 ]

其它的方法https://stackoverflow.com/questions/3506678/in-django-how-do-i-select-100-random-records-from-the-database

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容