Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between raw sql queries & normal sql queries?

Tags:

python

sql

django

I am kind of new to sql and database & currently developing website in django framework.

During my reading of django documentation I have read about raw sql queries which are executed using Manager.raw() like below.

for p in Person.objects.raw('SELECT * FROM myapp_person'):
Manager.raw(raw_query, params=None, translations=None)

How does raw queries differes from normal sql queries & when should I use raw sql queries instead of Django ORM ?

like image 300
Moon Avatar asked Oct 19 '25 09:10

Moon


2 Answers

Django (like other similar ORM tools) is a connection between relational databases and object-oriented programming. One of the very important functions that it implements is providing a uniform interface to the database -- regardless of the underlying database.

When you use underlying Django functionality, the code should be supported on any database (there may be specific limits on this). This makes it particularly easy to port to another database. It also helps ensure that the generated queries do what you intend.

When you use raw SQL, the code is likely to be specific to one database (creating a porting problem). The code is also not checked, which can result in hard-to-understand errors.

I have a strong preference for using SQL directly -- but that is because I am not a programmer using an ORM framework. If you are going to use such a framework, it is probably better to use the built-in functionality wherever possible.

like image 64
Gordon Linoff Avatar answered Oct 21 '25 23:10

Gordon Linoff


This is a borderline opinion question so might get flagged, but it is a good point. Essentially the raw SQL queries are intended to only be used for the edge cases where the Django ORM does not fulfil your needs (and with each new version of Django it support more and more query types so raw becomes less useful).

In general I would suggest using the ORM for the more helpful error messages, maintainability, and plain ease of use, and only use raw as a last-resort

like image 41
rsomji Avatar answered Oct 21 '25 22:10

rsomji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!