the red penguin
HOME ABOUT SITEMAP BLOG LOGIN

19. An introduction to the Object-Relational Mapper

One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL.

In fact, Django’s ORM is just a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion. It’s really clever engineering that takes advantage of some of the more complex parts of Python to make developers’ lives easier.

We can consider some pseudocode which demonstrates how we might query a database, send the answer to result, parse to an array, create a new object instance called this_user and then extract information into a variable called Name:

query = 'SELECT name, age FROM users WHERE uid=15'
result = database_handle.send_sql(query)
data_array = ParseToArray(result)
this_user = new User(data_array)
Name = this_user['name']

Django has a class called model which handles all of these operations. The pseudocode in Django would be a lot more terse:

Result = User.get_by_id(object_id)
name = result.name

This process of translating objects to database entities and back again is called Object Relationship Mapping or ORM.

This typically works well when objects and single database tables can be easily and conceptually mapped onto one another.

ORM does have some shortcomings:

  • Objects are hierarchical, tables are not
  • Objects are flexible to model graphs
  • Type mismatches between programming languages and RDBMS
  • Differing degrees of atomicity

These shortcomings are known as object relational impedance mismatch.

For the vast majority of operations and database designs, these mismatches will likely not be a problem for your web application. You might spend many years building applications before encountering edge cases where object relational impedance mismatch arises.

Wednesday 3 November 2021, 455 views


Leave a Reply

Your email address will not be published. Required fields are marked *