Models¶
documentation: Models
The Django Model is an ORM (Object Relational Mapping) allowing to create a bridge between OO program and relational databases. As such, models are DB agnostic.
Tables¶
Thus, a Python class deriving from django.db.models.Model automatically translate to a
DB Table.
- The code
from django.db import models class Part(models.Model): MPN = models.CharField(max_length=30) MFGR = models.CharField(max_length=30)
and resulting SQL
CREATE TABLE quesoloco_part ( "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY, "MPN" varchar(30) NOT NULL, "MFGR" varchar(30) NOT NULL );
When the model changes, Django provides a mechanism to create Migrations to update the DB backend to migrate to the new model definition.
Fields¶
Fields are defined as class attribute. An exhaustive list of Model field reference is available in the documentation.
By default, Django will generate an automatic primary key field (id) for each object types (table).
It is however possible to change that default to a custom one (e.g. UID) and have a custom generator.