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

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

问题描述

我有一个模型来代表我在我的网站上展示的画作.在主网页上,我想展示其中一些:最新的、大部分时间未访问的、最受欢迎的和随机的.

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.

我使用的是 Django 1.0.2.

I'm using Django 1.0.2.

虽然使用 django 模型很容易拉取前三个,但最后一个(随机)给我带来了一些麻烦.在我看来,我可以对其进行编码,如下所示:

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?

推荐答案

使用 order_by('?') 将在生产的第二天杀死数据库服务器.更好的方法类似于 从关系数据库中随机获取一行.

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天全站免登陆