Anubhav Singhal 🌻Which every technology you use for backend,
You don't have any excuse not to use ORM. semicolon.06:15 AM - 18 Jun 2021
Interacting with the database is a key component of an application and the manner that we do it makes a big impact in the process of development and user experience.
There are several techniques, one of which is ORM. Let's talk in depth about it.
Note: I'll be using Django as a reference, but the same principles apply almost everywhere.
ORM is an acronym that stands for Object Relational Mapping. An object is what you use in your programming language, a relation is your database, and mapping is the link between the two.
ORM is a technique that lets you query and manipulates data from a database using an object-oriented paradigm. It encapsulates the code needed to communicate with the database, so you don't use SQL anymore; you interact directly with an object in the same language you're using.
Read more at What is an ORM, how does it work
In ORM, Querysets are known to be lazily loaded in order to load only what is required rather than the entire database.
Lazy loading means that until you perform certain actions on the queryset, such as iterating over it, the corresponding DB query won't be made.
result= Person.objects.all() # Query hasn't been executed yet temp=result.filter(age__lt=45) # Query still hasn't been executed for obj in temp: print(obj) # Now query has been excecuted
Interacting with large databases is a time consuming task, that's why Querysets are cached. The primary motive for ORM caching is to increase performance through localised data access as an alternative to making a database round trip to retrieve it.
For e.g. (Continued from last example)
result= Person.objects.all() # Query hasn't been executed yet temp=result.filter(age__lt=45) # Query still hasn't been executed for obj in temp: print(obj) # Now query has been excecuted for obj in temp: print(obj.age,": ", obj) # Query hasn't been executed this time, because of caching.
Production: You don't have to be an expert in SQL queries, since you don't have to write SQL. Also, a lot of stuff is done automatically, hence Your code becomes short, clean, and easy to maintain.
Flexibility: it is generally available in the language of your choice, and lets you use OOPs goodness like inheritance very easily.
- ORM has tendency to slow down a little, as compared to direct communication with SQL.
- Developer has to go through ORM library, and understand it's functions and utilities so as to be able to use it efficiently.
To summarise, I believe in most of the use cases benefits of using ORM easily exceeds drawbacks. I've been using ORM for a while now, and it's significantly improved my development experience.
What do you think? Put down in the comments. As always suggestions are always welcome.