开发者

How to select 30 unique random values from database(MySQL) with django?

开发者 https://www.devze.com 2023-03-02 04:35 出处:网络
I\'ve read this question: In Django, how do I select 100 random records from the database? And tried to use Content.objects.all().order_by(\'?\')[:30], but this will produce some duplicate items. So h

I've read this question: In Django, how do I select 100 random records from the database?

And tried to use Content.objects.all().order_by('?')[:30], but this will produce some duplicate items. So how could I select 30 unique random valu开发者_JS百科es from database?


If you have a manageable number of entries in the database (ie not thousands), this will work, and even though it hits the db twice it will probably be much more efficient than order_by('?').

import random
content_pks = Content.objects.values_list('pk', flat=True)
selected_pks = random.sample(content_pks, 30)
content_objects = Content.objects.filter(pk__in=selected_pks)
0

精彩评论

暂无评论...
验证码 换一张
取 消