Search⌘ K

Models in Code

Explore how to structure Django model classes with different field types and establish relationships. Understand how to migrate the database automatically and set up the Django admin interface to manage your data. This lesson helps you create models, register them, and use superuser accounts for database interaction.

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:

Python 3.5
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 and that it is derived from the Model class.

Now, we have to define the properties of the post: title, ...