我正在使用Python/Django,但我懷疑這將不得不在mysql級別完成。在SQL中添加一個隨機性元素,django
如果我有一個模型,如:
class Article(models.Model):
title = models.CharField(max_length = 256)
rating = models.IntegerField(default=0)
我想查詢與收視率最高的文章,但我想添加隨機因素。我不只是要他們都擁有100評級出來的100
如果我這樣做在Python我會做類似
articles = Article.objects.all()
#multiply each rating by a random multiplier and store that value in a tuple with the article
articles = [(random.random()*article.rating, article) for article in articles]
#sort by the calculated rating*random value
articles.sort(key=lambda tup: tup[0], reverse=True)
這也許就是我能做的最好的。但是如果我要藉此降低到查詢級別,這是所有我到目前爲止有:
articles = Article.objects.extra(select={"rand_rating":'(rating * {})'.format(random.random())})
articles = articles.extra(order_by=['rand_rating'])
乍一看我還以爲可能會奏效,但random.random()號正要用一種基本上無用的常數乘以一切。我查看了SQL RAND(),但是從我讀過的內容來看,我將遇到同樣的問題,因爲每行不會調用RAND(),而只是每個查詢一次。
可能相關:[如何混合查詢集結果?](http://stackoverflow.com/q/12073425/1025391) – moooeeeep 2014-10-30 18:01:09