Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Models in Django

What is a Model?

In Django, a model is a Python class that represents a table in the database. Models are the single, definitive source of data for your application. They contain the essential fields and behaviors of the data you’re storing. Django follows the DRY (Don't Repeat Yourself) principle, so you define your data model in one place and then use it to create the database schema, query your data, and validate your data forms.

Creating a Basic Model

To create a model in Django, you define a class in the models.py file of your Django application. This class should inherit from models.Model.

Example:


from django.db import models

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    birth_date = models.DateField()

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

                

Field Types

Django provides a variety of field types to define the data that can be stored in a model. Some common field types include:

  • CharField: A string field, for small to large-sized strings.
  • TextField: A large text field.
  • IntegerField: An integer field.
  • DateField: A date field.
  • BooleanField: A true/false field.

Each field type has several optional arguments that can be used to customize its behavior. For example, CharField requires a max_length argument, which specifies the maximum length of the string.

Migrations

After defining your models, you need to create the database tables to store your data. Django uses migrations to propagate changes you make to your models into your database schema.

Run the following commands to create and apply migrations:


python manage.py makemigrations
python manage.py migrate

                

The makemigrations command creates new migration files based on the changes you have made to your models. The migrate command applies these migrations to your database.

Querying the Database

Once your models are defined and your database is set up, you can start querying your database using Django's ORM (Object-Relational Mapping). The ORM provides a high-level API for interacting with your data.

Example:


# Import the model
from myapp.models import Author

# Create a new author
author = Author(first_name="John", last_name="Doe", birth_date="1980-01-01")
author.save()

# Query the database
authors = Author.objects.all()
for author in authors:
    print(author.first_name, author.last_name)

                

Model Methods

You can define custom methods on your model to add additional functionality. These methods can perform any action you need, such as calculating values or formatting output.

Example:


class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    birth_date = models.DateField()

    def full_name(self):
        return f"{self.first_name} {self.last_name}"

    def __str__(self):
        return self.full_name()

                

Model Inheritance

Django supports model inheritance, which allows you to create a base model with common fields and then create child models that inherit from the base model.

Example:


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

class Student(Person):
    enrollment_date = models.DateField()

class Teacher(Person):
    hire_date = models.DateField()

                

Conclusion

Models are a fundamental part of any Django application. They allow you to define the structure of your data, create database tables, and interact with your data using Django's powerful ORM. By understanding models, you can effectively manage and query your application's data.