Django inertia mechanism
The so-called inertia mechanism: Publisher.objects.all () or. Filter () All just returns a queryset (query result set object), which does not execute SQL immediately, but executes when calling Queryset.
An iterative iteration of the inertia mechanism
# objs=models. Book.objects.all () # [obj1,obj2,ob3 ...] # for Obj in Objs: # Each obj is a row object that executes sql# print ("obj:", obj)
The possible slicing of inert mechanism
# objs=models. Book.objects.all () # [obj1,obj2,ob3 ...] # print (objs[1]) # print (Objs[1:4]) # print (Objs[::-1])
The Django cache problem of inertia mechanism
Django has its own cache, and if 2 times the Obj object is consistent, the second check value is taken directly from the cache.
If the contents of the period database are changed, you need to re-check the values. Otherwise, dirty data can be generated easily.
You can directly use the first obj object for the update operation, so that the next time for a loop query to re-execute the database query operation, the cache is also changed, you can re-check the results manually, but it is not recommended, because we do not know when the data will be modified, Whether or not Django uses the data itself to query the results of the data
Note 1: If there are data changes between the 2 operations, you need to re-check the values from the database, or Django will pull the data out of the cache, affecting the final query results.
# objs=models. Book.objects.all () # [obj1,obj2,ob3 ...] # for Obj in Objs: # Each obj is a row object that executes SQL # print ("obj:", obj) Models.Bool.update.get (id=2). Update ( ' Title ' = ' YYY ') # Changes in the database, the cache has not changed # Objs=models. Book.objects.all () re-locate and assign values from the database to objs# objs.update (title= ' YYY ') is recommended, the direct database/memory has changed, the following for loop query when the database was re-executed # Objs=models. Book.objects.all () # [obj1,obj2,ob3 ...] # for Obj in Objs: # print ("obj:", obj) # or Objs object, so take a value from the cache
correct operation :
1. Re-execute the query objs=models. Book.objects.all () "Not recommended"
2. Use of Objs.update (title= ' YYY '); Now that the database has changed, the values in the cache have also changed
NOTE 2:
If Objs (): queries the database and puts all the data results of the query into the database if Objs.exist (): queries the database only, but does not put all the data in the database, if Obj.iterator (): Data into the iterator, Take one iteration at a time
Python Learning---Django inertia mechanism