Home > Backend Development > Python Tutorial > Several small methods to improve the efficiency of Django model

Several small methods to improve the efficiency of Django model

高洛峰
Release: 2016-10-17 14:03:40
Original
1068 people have browsed it

Django’s model is not very efficient, especially when doing a lot of database operations. If you only use django to open a corporate website or outsourcing projects, you can skip it a little bit, and you happen to be an efficiency freak or... If the efficiency requirements of the program are relatively high, then you should pay attention to the following methods.
1. count() method:
If we want to use the count method to get the number of records, we can use the following method:
num = info.objects.filter('...').count()
Let's take a look How to write the count method in the django model module?
def count(self):
"""
Performs a SELECT COUNT() and returns the number of records as an
integer.
If the QuerySet is already fully cached this simply returns the length
of the cached results set to avoid multiple SELECT COUNT(*) calls.
"""
if self._result_cache is not None and not self._iter:
return len(self._result_cache)
return self.query.get_count(using=self.db)

From the above, the count() of djang model needs to execute the SELECT COUNT() statement, which actually queries the database. In this way, if there are many records, the efficiency of querying the database is relatively high. For example, we can If you use the len() method to find the length, the iteration used will be less effective.
info = info.objects.filter('...')
num = len(info)
2 Multi-use slicing
For example, if we want to query data, if your data volume is relatively large, you have no limit to query The scope of the system will be very large. For example, if you want to display
news data in pages, then you have to read as much data as you want to display on one page, instead of reading all the data at once. , and then display the data according to the defined conditions.
For example, if you want to display the top 10 news items, do it as follows:
news = News.objects.all()[1:10]
Instead of:
news = News.objects.all()
news = news[1:10]
Because
news = News.objects.all()
news = news[1:10]
You are reading all the data in the database, which is not very efficient.
The points mentioned above are some small methods to improve the efficiency of Django model. I hope everyone will pay attention to some efficiency things when developing projects with Django.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template