Define Models
Quick example
Although you can use Django without a database, it comes with an object-relational mapper in which you describe your database layout in Python code.
The data-model syntax offers many rich ways of representing your models – so far, it’s been solving many years’ worth of database-schema problems.
Here’s a quick example:
#[app name]/models.py
from django.db import models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
def __str__(self):
return self.full_name
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
def __str__(self):
return self.headline
first_name and last_name are fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column.
The above Person model would create a database table like this:
CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);
Some technical notes:
- The name of the table,
myapp_person, is automatically derived from some model metadata but can be overridden. See Table names for more details. - An
idfield is added automatically, but this behavior can be overridden. See Automatic primary key fields. - The
CREATE TABLESQL in this example is formatted using PostgreSQL syntax, but it’s worth noting Django uses SQL tailored to the database backend specified in your settings file.