Django Models

By: Dusty Arlia
Published on Tuesday, February 11, 2014, 08:22 PM
Last Updated on Tuesday, July 07, 2015 at 10:32 PM
Total Updates: 2

A Django model is a Python class that represents a single database table, and an instance of that class represents a particular record in the database table. Models do this by mapping to the database table. They contain the fields and the behavior of the data you're storing. Models define your database's layout and your database's metadata. They provide the data about your data. You should define your data model in one place and automatically derive things from it.

Models are Python classes. These classes are subclasses of django.db.models.Model. Each model attribute (variable) represents a database field in the model. Each field is represented by an instance of a Field class like CharField (for character fields), IntegerField (for integers), and DateTimeField (for datetimes). These subclasses of Field help Django know the types of data stored in the fields.

Here is a basic example found in your your_app/ file:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

This Person model would create a database table like this (The CREATE TABLE SQL in this example is formatted using PostgreSQL syntax, but Django uses SQL based on the database backend specified in your file.):

CREATE TABLE your_app_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(100) NOT NULL,
    "last_name" varchar(100) NOT NULL

The name of the table is your_app_person. It is automatically generated from the model metadata. You are able to change this to a different name if you really wanted to.

An id field is added automatically, but this behavior can be overridden.

The name of each Field instance, in this case first_name and last_name, are the names of the fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column.

Some Field classes have required arguments. For example, CharField requires a max_length argument. Fields can also have optional arguments, such as default values. A model can form a relationship with another model using a ForeignKey.

Using models, you are able to create a database schema and an API (using Python) for accessing the database. This API will allow you to access Person objects. Django also gives you an automatically-generated database-access API