Models in Code
Let's learn about the structure and syntax of writing models in Django.
We'll cover the following...
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 settingsfrom django.db import modelsfrom django.utils import timezoneclass 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 thePost
is a Django model ...