简体   繁体   English

count()是计算对象数量的最有效方法吗?

[英]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.

相关问题 如何以最有效的方式按组统计高分值的数量? - How to count the number of high score values by group in the most efficient way? 最有效的分组,计数,然后排序的方法? - Most efficient way to group, count, then sort? 在对象上计数的最有效方法是什么? - What is the most efficient way to count votes on an object? Python多维数组 - 计算非零项数量的最有效方法 - Python Multidimensional Arrays - most efficient way to count number of non-zero entries 在python的时间范围内,最有效的计数实例数量的方法是什么? - What is the most efficient way to count the number of instances occurring within a time frame in python? 在列表 python 上计算大数字的有效方法 - Efficient way to count big number on list python 计算每行的子数据帧行的最有效方法是什么? - Most efficient way to count sub-dataframe rows for each row? Python:计算路径中父文件夹的最有效方法 - Python: Most efficient way to count the parent folders in a path 计算连续重复值的计算效率最高的方法 - Most computationally efficient way to count consecutive repeating values 在Python中使用XPath计数节点的最有效方法 - Most efficient way to count nodes using XPath in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM