如何使用Django的ORM拉一个随机记录? [英] How to pull a random record using Django's ORM?

查看:141
本文介绍了如何使用Django的ORM拉一个随机记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,代表我在我网站上出现的绘画。在主要网页上,我想展示其中的一些:最新的,大多数时间没有访问的,最受欢迎的和随机的。



我正在使用Django 1.0.2。



虽然前3个容易使用django模特儿,最后一个(随机的)让我有些麻烦。我可以在我的视图中对它进行编码,如下所示:

  number_of_records = models.Painting.objects.count()
random_index = int(random.random()* number_of_records)+1
random_paint = models.Painting.get(pk = random_index)

它看起来不像我想要的东西 - 这完全是数据库抽象的一部分,应该在模型中。另外,在这里我需要处理已删除的记录(然后所有记录的数量都不会覆盖我所有可能的关键值),并且可能还有很多其他的东西。



任何其他选项,我可以如何做,最好是在模型抽象的内部?

解决方案

使用 order_by '?')将在生产的第二天杀死数据库服务器。一个更好的方法就像在从关系数据库获取随机行

  from django.db.models.aggregates import count 
from random import randint

class PaintingManager(models.Manager):
def random(self):
count = self.aggregate(count = Count('id'))['count']
random_index = randint(0,count - 1)
return self.all()[random_index]


I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one.

I'm using Django 1.0.2.

While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:

number_of_records = models.Painting.objects.count()
random_index = int(random.random()*number_of_records)+1
random_paint = models.Painting.get(pk = random_index)

It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.

Any other options how I can do it, preferably somehow inside the model abstraction?

解决方案

Using order_by('?') will kill the db server on the second day in production. A better way is something like what is described in Getting a random row from a relational database.

from django.db.models.aggregates import Count
from random import randint

class PaintingManager(models.Manager):
    def random(self):
        count = self.aggregate(count=Count('id'))['count']
        random_index = randint(0, count - 1)
        return self.all()[random_index]

这篇关于如何使用Django的ORM拉一个随机记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆