[英]Is count() the most efficient way to count the number of objects?
I need to count the number of objects of a particular model in my database and display the number with a context processor for the user to view on every page. 我需要计算数据库中特定模型的对象数量,并使用上下文处理器显示该数量,以供用户在每个页面上查看。
Right now I'm simply doing Model.objects.count()
. 现在,我只是在做Model.objects.count()
。 It works, but as there are now more than 400,000 objects in the db, it has noticeably slowed things down. 它可以工作,但是由于数据库中现在有超过40万个对象,因此它的运行速度明显降低。
I'm running on my development server, so maybe once I push to dedicated servers this won't be a problem, but I'm not sure... I'm worried what will happen once we get into the millions or beyond. 我正在开发服务器上运行,因此也许一旦我推到专用服务器上就不会有问题,但是我不确定...我担心一旦我们进入数百万或更多的领域,将会发生什么。 Any tips? 有小费吗?
If the estimate you get from pg_class.reltuples
is good enough, go for it. 如果从pg_class.reltuples
得到的估计值足够好,那就去做。 That would be the simplest solution. 那将是最简单的解决方案。
If you need exact numbers, you could do that with a trigger. 如果您需要确切的数字,则可以使用触发器来完成。 The following example keeps a count of the table mytab
in mytab_count
: 以下示例将表mytab
的计数保留在mytab_count
:
CREATE TABLE mytab_count (
c bigint NOT NULL
);
-- make sure there cannot be more than one row
CREATE UNIQUE INDEX mytab_count_singleton
ON mytab_count ((1));
INSERT INTO mytab_count
SELECT count(*) FROM mytab;
CREATE OR REPLACE FUNCTION count_trig() RETURNS trigger
LANGUAGE plpgsql AS
$$BEGIN
CASE TG_OP
WHEN 'INSERT' THEN
UPDATE mytab_count SET c = c + 1;
RETURN NEW;
WHEN 'DELETE' THEN
UPDATE mytab_count SET c = c - 1;
RETURN OLD;
END CASE;
END;$$;
CREATE TRIGGER count_trig AFTER INSERT OR DELETE ON mytab
FOR EACH ROW EXECUTE PROCEDURE count_trig();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.