From my past post:

https://me.chrisdevcode.com/posts/django-architecture-models-views-templates/

In Django, a model is what defines your database table. It’s basically a python class that maps to a single table in your database. For example, class Users will simply be the Users table:

class Users(models.Model):
    full_name = models.CharField(max_length=200)
    bio = models.TextField()

    def __str__(self):
        return self.full_name

Django’s documentation on models: https://docs.djangoproject.com/en/5.2/topics/db/models/

In Django, a model is a special type of object that represents and stores data in the database.

A database is simply a structured collection of data — where you keep information such as users, blog posts, and more.

By default, Django uses SQLite, which is a lightweight, file-based database that’s “cool” for development purposes.

You can imagine a model like a spreadsheet: each column is a field, and each row is a record of data.

Defining Models

Creating a model in django is done in a models.py file that is found inside a django app upon creating an app.

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=255)
    author = models.CharField(max_length=100)
    published_date = models.DateField()
    price = models.DecimalField(max_digits=6, decimal_places=2)
    in_stock = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

class Book(models.Model): – this line defines our model (it is an object). It defines the “name” of teh database table.

Book is the name of the model. We can give it a different name (but we must avoid special characters and whitespace). Always start a class name with an uppercase letter. Models.Model means that the Post is a Django Model, so Django knows that it should be saved in the database. - edited from the Django Girls Tutorial

We then define the properties of the class, in this case, columns: title, author, published_date, price, ins_stock and created_date. To do that, we need to define the type of each field (Is it text? A number? A date? A relation to another object, like a User?)

  • models.CharField – this is how you define text with a limited number of characters.
  • models.TextField – this is for long text without a limit. Sounds ideal for blog post content, right?
  • models.DateTimeField – this is a date and time.
  • models.DecimalField - this for numeric values with decimal places
  • models.BooleanField - this is boolean

Extra Resources — Written

  1. https://docs.djangoproject.com/en/5.2/topics/db/models/
  2. https://tutorial.djangogirls.org/en/django_models/