Working and interacting with databases is an essential part of building web applications. This is a task that you want to pay great attention to as a web developer as it can cost you and your organisation a fortune if not well managed. When it comes to building with Django, this heavy task has been made easy and convenient through its Object-Relational Mapping (ORM) by simply turning database operations into Python code.
Developers love Django’s ORM for its simplicity and flexibility. The fact is that they don’t have to write raw SQL queries every now and then to perform database operations. In fact, there are many who only know very basic SQL because why should they go through the stress? All operations can be performed with Python quickly and easily. It also makes their codes very clean and readable.
While we can all agree that this is a very powerful tool, we should also agree to the fact that Django’s ORM is not entirely perfect for every situation especially when it comes to writing complex queries, working with large amounts of data or when performance optimization is important. In these situations, writing raw SQL produces better results.
In the case of writing Raw SQL, developers are always given optimal control over database queries which makes it easy to flexibly write complex queries when necessary. However, writing Raw SQL requires an in-depth understanding of database internals and can as well introduce potential security vulnerabilities if not properly handled.
I will be starting this talk by providing a clearer overview of Django's ORM and how database interactions can be simplified with it. I will go from highlighting common cases where Django’s ORM excels, such as simple CRUD operations and basic data manipulation tasks, to mentioning some of the advanced features of Django’s ORM, including querysets, annotations, and aggregation.
After that, I will also give an introduction to the world of Raw SQL and how it's different from Django’s ORM. I will explain the situations when it’s best appropriate to bypass Django’s ORM and use Raw SQL instead. I will explore cases that involve performance-critical operations, complex data joins, and advanced database-specific operations that are best performed with Raw SQL.
Throughout the talk, I will provide practical examples and demonstrations to illustrate every one of my points. The aim is to let attendees better understand when to use Django’s ORM and when to bypass it in favour of Raw SQL. I will try my best to achieve this within the limited time I shall be given.
By the end of the session, attendees will have gained valuable insights into the strengths and weaknesses of Django's ORM and Raw SQL, which will help them in making decisions as to which of these to use when building web applications with Django.