Django models

Prerequisites

Django Model

  • Django model serves as a blueprint for creating and managing data, representing a single table in the database.
  • Each model maps to a database table, and each instance of a model represents a record (or row) in that table.

Defining a Model

  • To create a model, you define a class that inherits from django.db.models.Model
  • Each attribute of the class represents a database field.
  • Lets look at the sample django model below.

my_app/models.py

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    published_date = models.DateField()
    isbn = models.CharField(max_length=13)
    pages = models.IntegerField()
    cover_image = models.ImageField(upload_to='covers/', null=True, blank=True)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['title']
        verbose_name_plural = "Books"
        db_table = "book"
  • In the example above:

    • The Book class is our model, representing a table called book.
    • The attributes like title, author, and published_date are the fields of our model, representing columns in the database table.

Model Fields

Django provides a wide variety of field types that you can use to define your models, such as:

  • CharField: A string field for small-to-medium-sized strings.
  • TextField: A large text field, suitable for large bodies of text.
  • IntegerField: Stores integers.
  • FloatField: Stores floating-point numbers.
  • BooleanField: Stores True or False values.
  • DateField / DateTimeField: Stores date or date/time values.
  • EmailField: Validates and stores an email address.
  • URLField: Stores a URL.

For a complete list of fields, refer to the Django documentation on fields.

Common Field Options

  • We can customize how fields behave by passing options to them:
  • null: If True, Django will store NULL in the database for empty values.
  • blank: If True, the field is allowed to be blank in forms.
  • default: Specifies a default value for the field.
  • unique: If True, ensures all values in this field are unique across rows.
  • choices: Limits field values to a specified list of choices.

Model Meta Options

  • The Meta class within a model allows you to define additional options, such as ordering, table names, and more.
  • If we look at the Book model we can find below things.

    • ordering: Specifies the default ordering for records when retrieved.
    • verbose_name_plural: Changes the plural name for the model in the admin interface.
    • db_table: Specifies the table name in the database.

References: