Models in Code

Let's learn about the structure and syntax of writing models in Django.

Structure of model class

As we mentioned in the previous lesson, we have model classes that inherit from Django’s built-in models.Model class.

Let’s look at an example of a blog post to see the structure of a Model class:

Press + to interact
from django.conf import settings
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)

Let’s break down and analyze the code lines one by one:

First, we imported some useful libraries.

class Post(models.Model): – this line defines our model (it is an object).

  • class is a special keyword that we use in Python to define classes.

  • Post is the name of our model.

  • models.Model means that the Post is a Django model ...