No history yet

Introduction to Django Models

Models The Heart of Your Data

At its core, every web application manages data. In Django, the way we structure and interact with that data is through models. A Django model is the single, definitive source of information about your data. Think of it as a blueprint. A blueprint for a house defines its rooms, dimensions, and materials. A Django model defines the fields and behaviors of the data you’re storing.

Essentially, a model is just a Python class. Each attribute of the class represents a database field. With this simple Python class, Django can create a database table for you, and it gives you a simple Python API to access and manipulate your data, without having to write a single line of SQL.

By enabling developers to deal with database models using Python code rather than SQL queries, Django's Object-Relational Mapping (ORM) streamlines database interactions.

Defining a Simple Model

Let's create a model for a simple blog post. We need a place to store a title, the main content, and the date it was published. In Django, this looks like a straightforward Python class that inherits from django.db.models.Model.

from django.db import models

class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    pub_date = models.DateTimeField('date published')

In this example:

  • BlogPost is our model. Django will create a database table named something like yourapp_blogpost.
  • title, content, and pub_date are the fields. These will become the columns in our database table.
  • Each field is an instance of a Field class, like CharField or DateTimeField. This tells Django what kind of data to store.

Field Types and Options

Django comes with a wide variety of field types that cover most common needs. Choosing the right one ensures your data is stored correctly and efficiently.

Field TypeDescriptionUse Case
CharFieldA field for short-to-medium length strings.Storing a title, a name, or a city.
TextFieldA large text field.Storing blog post content or a long description.
IntegerFieldAn integer.Storing a product quantity or a user's age.
DateTimeFieldA date and time.Storing a publication date or an event timestamp.
BooleanFieldA true/false field.Storing a setting like is_published.

Each field type also accepts various arguments, called options. For example, max_length=200 in our CharField is an option. It tells the database to limit the length of the title. Another common option is default, which sets a default value for a field if one isn't provided.

For example, you could add a field for the number of likes with a default value of zero: likes = models.IntegerField(default=0).

Model Methods and Properties

A model class isn't just for defining database structure; you can also add custom methods to give your objects behavior. A common method to add is __str__(). This method tells Python how to display a user-friendly representation of the object, which is incredibly helpful in the Django admin site and for debugging.

from django.db import models

class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.title

Now, if you were to print a BlogPost object, you would see its title instead of a generic object description like <BlogPost: BlogPost object (1)>.

Relationships Between Models

Data is rarely isolated. Blog posts have authors. Products have categories. Students have teachers. Django allows you to define these relationships directly in your models using special field types.

The most common relationship is a many-to-one relationship, which you create using ForeignKey. For instance, many blog posts can be written by a single author. To model this, we'd first create an Author model and then link our BlogPost model to it.

class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

    def __str__(self):
        return self.name

class BlogPost(models.Model):
    # ... same fields as before ...
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

The ForeignKey field creates the link. The on_delete=models.CASCADE part is important; it tells Django that if an author is deleted, all of their blog posts should be deleted as well. This maintains the integrity of your data.

Quiz Questions 1/5

In the context of a database, what does a Django model class primarily represent?

Quiz Questions 2/5

What is the main purpose of adding a __str__() method to a Django model?