Django Models

Models are the data accees layer of your application. Every django application gets a file by default to create database tables. The default database engine in django framework is sqlite3. It can be changed by visiting under project directory. Django uses ORM (Object Relational Mapping) that allows us to perform database operations without writing SQL queries but with simple python objects.

from django.db import models

models is a module that packs the definitions for Model classes, different models fields and field relationships.
To create a table in simply make a class subclassing the Model class.

class MyClassname(models.Model): ...

Django Model Fields

Django version 2.2 offers 26 different field types to capture different data formats. For simplicity we have grouped them according to functionality rather than alphabetical sorting.

Django Models - Field Types

  • AutoField
  • BigAutoField
  • UUIDField
  • IntegerField
  • PositiveIntegerField
  • SmallIntegerField
  • PositiveSmallIntegerField
  • BigIntegerField
  • DecimalField
  • FloatField
  • BinaryField
  • BooleanField
  • NullBooleanField
  • CharField
  • TextField
  • EmailField
  • SlugField
  • URLField
  • GenericIPAddressField
  • DateField
  • TimeField
  • DateTimeField
  • DurationField
  • FileField
  • FilePathField
  • ImageField

Django Models - Field Options

The following arguments are available in Django field types:

  • null
  • blank
  • choices
  • db_column
  • db_index
  • db_tablespace
  • default
  • editable
  • error_messages
  • help_text
  • primary_key
  • unique
  • unique_for_date
  • unique_for_month
  • unique_for_year
  • verbose_name
  • validators

Django Models - Field Relationships

Sometimes business logic require relationships among attributes of different model classes. Their are three field relationships in django models: ForeignKey(), OneToOneField() and ManyToManyField().

Django ForeignKey

ForeignKey is like a many-to-one relationship. It requires two positional arguments namely Classname and on_delete.
Classname is the class to which model is related.
on_delete=models.CASCADE means when the Super class object is deleted all its reflections as ForeignKey also gets deleted. For example when the Customer object in below model is deleted it's related Order objects are also deleted.

    class Customer(models.Model):
        name = models.CharField(max_length=30)
        def __str__(self):
    class Order(models.Model):
        customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
        order_details = models.TextField()

Django OneToOneField

OneToOneField is very similar to ForeignKey except the realtionship is like unique=True.
For example, if one Person can be have only one nationality it can described as below:

    class Person(models.Model):
        name = models.CharField(max_length=30)
        def __str__(self):
    class Citizenship(models.Model):
        person = models.OneToOneKey(Person, on_delete=models.CASCADE)
        country = models.CharField(max_length=30)

Django ManyToManyField

A many-to-many relationship requires only one argument i.e, the class to which the model is related. It can be understood with the example below:

    class Person(models.Model):
        name = models.CharField(max_length=30)
    class Group(models.Model):
        name = models.CharField(max_length=128)
        members = models.ManyToManyField(
            through_fields=('group', 'person'),
    class Membership(models.Model):
        group = models.ForeignKey(Group, on_delete=models.CASCADE)
        person = models.ForeignKey(Person, on_delete=models.CASCADE)
        inviter = models.ForeignKey(
        invite_reason = models.CharField(max_length=64)