Friday, April 17, 2020

Django Models

Django’s models provide an Object-relational Mapping (ORM) to the underlying database. ORM is a powerful programming technique that makes working with data and relational databases much easier.
Most common databases are programmed with some form of Structured Query Language (SQL), however each database implements SQL in its own way. SQL can be quite complex and difficult to learn. An ORM tool on the other hand, provides a simple mapping between an object (the ‘O’ in ORM) and the underlying database, without the programmer needing to know the database structure, or requiring complex SQL to manipulate and retrieve data (Figure shown below).

Django Tutorials - Django ORM
In Django, the model is the object that is mapped to the database. When you create a model, Django creates a corresponding table in the database (Figure shown below), without you having to write a single line of SQL. Django prefixes the table name with the name of your Django application (more on Django applications later).
Django Tutorials - Model Table

The model also links related information in the database. In Figure shown below, a second model is created to keep track of the courses a user is enrolled in. Repeating all the users information in the yourapp_Course table would be against good design principles, so we instead create a relationship (the ‘R’ in ORM) between the yourapp_Course table and the yourapp_UserProfile table.
Django Tutorials - Model Relationships

This relationship is created by linking the models with a foreign key—in other words the user_id field in our yourapp_Course table is a key field that is linked to the id field in the foreign table yourapp_UserProfile.
This is a bit of a simplification, but is a handy overview of how Django’s ORM uses the model data to create database tables.
Django officially supports four databases:
  • PostgreSQL
  • MySQL
  • SQLite
  • Oracle
There are also a number of third party applications for connecting to other databases, if you need to connect to an unofficially supported database. Django installs and configures SQLite automatically, with no input from you however, the preference for most Django developer is PostgreSQL. SQLite is for early development and testing. It should not be used in production. 
In the next post we'll discuss Django templates.


Share:

0 comments:

Post a Comment