With regards to upgrading an ORM, your most prominent weapon is your comprehension of how your ORM functions in the engine (essentially at a significant level). This makes seeing the principles in general and rules for making an expedient application a lot more straightforward. Accordingly, I enthusiastically suggest perusing the Django docs regarding the matter once. My objective for this post is to consolidate these tips and fools into an effectively referenceable assemblage, just as adding my very own portion. Likewise look at my Django ORM Optimization cheat sheet for a significantly more dense adaptation.
Maybe the main part of the Django ORM to comprehend is the manner by which QuerySets work. Since QuerySets are lethargically assessed, you can chain channel() and bar() the entire day without really hitting the data set. Pay special attention to this to assess QuerySets just when you really need to.
When QuerySets are evaluated:
# Iteration for person in Person.objects.all(): # Some logic # Slicing/Indexing Person.objects.all()[0] # Pickling (i.e. serialization) pickle.dumps(Person.objects.all()) # Evaluation functions repr(Person.objects.all()) len(Person.objects.all()) list(Person.objects.all()) bool(Person.objects.all()) # Other [person for person in Person.objects.all()] # List comprehensions person in Person.objects.all() # `in` checks
When QuerySets are not cached:
# Not reusing evaluated QuerySets print([p.name for p in Person.objects.all()]) # QuerySet evaluated and cached print([p.name for p in Person.objects.all()]) # New QuerySet is evaluated and cached # Slicing/indexing unevaluated QuerySets queryset = Person.objects.all() print(queryset[0]) # Queries the database print(queryset[0]) # Queries the database again # Printing print(Person.objects.all())
When QuerySets are cached:
# Reusing an evaluated QuerySet queryset = Person.objects.all() print([p.name for p in queryset]) # QuerySet evaluated and cached print([p.name for p in queryset]) # Cached results are used # Slicing/indexing evaluated QuerySets queryset = Person.objects.all() list(queryset) # Queryset evaluated and cached print(queryset[0]) # Cache used print(queryset[0]) # Cache used
Choosing correct ORM query can minimize the cached memory and leaves the less load on database. It is good practice and also reduce the load time of executing queries.