Why should I use Django ORM when I know SQL?
The main benefits of using Django ORM instead of SQL is a huge improvement in development speed, code maintenance, security and ease of development in general. Let’s talk about these in detail.
Development speed
Django ORM comes with a lot of built-in tools that speed up the development process dramatically. It supports: seamless schema generation and migration, common data relationships (many-to-many, many-to-one, etc) and queries with them, data validation and integrity, switching between various databases without rewriting code, etc. By using Django ORM you get the benefit of the whole Django infrastructure that is built on top of ORM, like Django Forms, Django Generic Views, serializers and a lot of 3rd party apps.
Code maintenance
With ORM it is much easier and less error-prone to modify the queries than with raw SQL. Code reuse is a nightmare when you deal with raw SQL: if you want to use a slightly modified query in another place you’ll need to basically copy paste the entire query just to modify a certain part of it.
Security
It is much easier to introduce security vulnerabilities when writing raw SQL. By using ORM exclusively you are guaranteed to be safe from SQL injections. However, as soon as you start to use unsafe raw
and extra
methods you increase the chance of introducing SQL injection vulnerabilities into your app.
Simplicity
This is a rather subjective one, but from a Python developer perspective dealing with Python code is more pleasant than memorizing another language syntax with all its quirks. Besides, some of the ORM queries are more straightforward than raw SQL. Finally, converting between the Python and SQL datatypes is another source of headaches.