3

I have my django app running on Server 1 which is connected to Amazon RDS (PostgreSQL) present on Server 2. On a day-to-day basis, I have to interact with database often to write/fetch/query data.

Currently, I am following the django ORM way across the app. I just wanted to know if there would be any improvement in the performance if I use PostgreSQL raw SQL queries using django.db connection cursor over ORM?

Following are the proposed ways for one sample query.

  1. Django ORM

    table_name.objects().all()
    
  2. PostgreSQL raw SQL queries using django.db connection cursor:

    enter image description here

Can someone please suggest which one of the above will lead to a faster increased in performance provided I have my database running on RDS in another server.

2
  • 3
    No, the overhead of the ORM is completely insigificant compared to a roundtrip to the database. Commented Jun 30, 2020 at 21:12
  • Django uses psycopg2 to communicate with PostgreSQL. Here's a good performance comparison of different methods for writing and reading using that library. There are also initiatives like this that try to make the fastest of them available in Django. However, if you already consider operating on raw SQL, using psycopg2 directly might be an easier, faster and more flexible approach than forcing Django to use it a certain way for you. Commented Jul 1, 2020 at 5:36

1 Answer 1

4

Using a raw query will result in close to no performance difference. The ORM indeed uses a few cycles to construct the query, but that is insignificant compared to the work of sending the query, the database receiving, interpreting and running the query, and sending the results back.

In some cases the ORM might indeed make a (over)complicated query, but that is not the case if you fetch all records. It sometimes requires ORM expertise (just like it requires expertise in SQL) to find a query that performs better.

You can furthermore already let the Django ORM do the work for you by using .values() to make it more convenient to construct a DataFrame:

res = pd.DataFrame(table_name.objects.values())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.