django queryset的一些技术

一、queryset.count() 和 len(queryset) 如何选择

Note: Don't use len() on QuerySets if all you want to do is determine the number of records in the set. It's much more efficient to handle a count at the database level, using SQL's SELECT COUNT(*), and Django provides a count() method for precisely this reason.

(most crucial) When you only want to know the number of elements and you do not plan to process them in any way it's crucial to use count():

DO: queryset.count() - this will perform single SELECT COUNT(*) some_table query, all computation is carried on RDBMS side, Python just needs to retrieve the result number with fixed cost of O(1)

DON'T: len(queryset) - this will perform SELECT * FROM some_table query, fetching whole table O(N) and requiring additional O(N) memory for storing it. This is the worst that can be done

简单说,如果只看长度,用count,如果循环取得数据,用len

猜你喜欢

转载自www.cnblogs.com/lxgbky/p/12468181.html