[PYTHON] [Day 9] Creating a model

January 14, 2021 ← Last time: Display template in Day 8 Template View

Precautionary statement

This article is not a single article. I wrote it as a diary, so I think it will be useful for those who are new to it. If you want to learn Django, we recommend reading it from [Day 1] Django Development Environment.


The theme this time is "Creating a model". So far, it's very rudimentary, but we've looked at View and Template. The rest is Model. Django has a mechanism that allows you to link with a database and perform validation processing smartly by giving various information to the model. This time, let's make a simple model and learn because it is a bulletin board.

Add thread application

First, create a thread application. This is an application that handles things related to bulletin board threads.

(venv)$ ./manage.py startapp thread

Add thread/urls.py, add application to mysite/settings.py, and add URL to mysite/urls.py as well as base application. This area is similar to the base application. [Day 4] Application Creation For reference


+     'thread',


  urlpatterns = [
      path('admin/', admin.site.urls),
      path('', include('base.urls')),
+     path('thread/', include('thread.urls')),


from django.urls import path

from . import views
app_name = 'thread'

urlpatterns = [

Now the additional processing of the application is OK.

Model addition

The thread application model is assumed to be as follows. First, consider the following model so that it has the minimum functions of the bulletin board.


from django.db import models

class TopicManager(models.Manager):
    #Added processing related to Topic operation

class CommentManager(models.Manager):
    #Added processing related to Comment operation

class CategoryManager(models.Manager):
    #Added processing related to Category operation

class Category(models.Model):
    name = models.CharField(
        'Category name',
    url_code = models.CharField(
        'URL code',
    objects = CategoryManager

    def __str__(self):
        return self.name

class Topic(models.Model):
    user_name = models.CharField(
    title = models.CharField(
        null = False,
        blank = False,
    message = models.TextField(
    category = models.ForeignKey(
    created = models.DateTimeField(
    modified = models.DateTimeField(
    objects = TopicManager()

    def __str__(self):
        return self.title

class Comment(models.Model):
    id = models.BigAutoField(
    no = models.IntegerField(
    user_name = models.CharField(
    topic = models.ForeignKey(
    message = models.TextField(
        verbose_name='Posted content'
    pub_flg = models.BooleanField(
    created = models.DateTimeField(
    objects = CommentManager()

    def __str__(self):
        return '{}-{}'.format(self.topic.id, self.no)

Brief commentary

From here, we will enter the above (thread/models.py) explanation. Therefore, I will post the URL of the head family. Honke After that, I will put the explanation below so that you do not have to jump to the link, but since it is exactly the same as the head family, it is recommended to fly to the head family and refer to it.

Model field

The properties of each class in the model are defined by the model fields. The official model field reference summarizes the model field types. In Django, it is ideal to collect the related information of the model in one place as much as possible, and add information such as data type at the time of database storage, relation information, default value, null tolerance, etc. In many Web developments, I think that implementation will start after completing API design and database design, so it will be a task to write the design straight to the model.

null and blank

I got null and blank. Does null allow nulls on the database? And blank is whether or not the user makes it a required item as an input item. Specifically, if you apply False to blank, the input tag will be required in the form.

Automatic ID generation

By the way, did you notice that there is no description about ID? If you don't specify the ID, Django will automatically generate it for you. In that case, the data type will be int and the Primary Key will be set.

Foreign key

This time, in order to build a one-to-many relationship, the topic has the category id and the comment has the topic id. In such cases, Django uses a Foreign Key. In that case, specify the deletion method with on_delete when the model held as a foreign key is deleted. The types are as follows.

models.CASCADE: Models referenced along with foreign key models are also deleted models.PROTECT: Protected (cannot be deleted if referenced) models.SET_NULL: ID will be NULL if the foreign key model is deleted models.SET_DEFAULT: The value set by default is set. Is PROTECT recommended? CASCADE is a little risky, but I don't think it's a problem depending on the design.

About the manager

In addition, this time we prepared TopicManager, CommentManager, CategoryManager and linked them with objects of each model. In the future, we will add processing related to operations related to each model to this manager, and call that processing from the view so that it acts on the model. Before I get used to it, View tends to do a lot of processing and it tends to be bloated, but I am thinking (with self-admonition) that the business logic processing that the model is responsible for should be done by the model. So far, I was able to explain it carefully, but I wasn't sure. However, I did understand what Django's model was like. # in conclusion This time I created a model. Having touched SQL at university, I was able to understand the nature of the model a little.

See you again

← Last time: Display template in Day 8 Template View → Next time: Day 10 Database Migration

Recommended Posts

[Day 9] Creating a model
Creating a learning model using MNIST
Creating a Home screen
4. Creating a structured program
Creating an interactive application using a topic model
Creating a scraping tool
Creating a dataset loader
Try creating a CRUD function
User is not added successfully after creating a custom User model
Block device RAM Disk Creating a device
Creating a Tensorflow Sequential model with original images added to MNIST
Creating a web application using Flask ②
Creating a wav file split program
Step by Step for creating a Dockerfile
Creating a decision tree with scikit-learn
Creating a Flask server with Docker
Creating a voice transcription web application
Creating a simple table using prettytable
Creating a simple app with flask
Inversely analyze a machine learning model
Creating a web application using Flask ①
[Python] Creating a scraping tool Memo
Precautions when creating a Python generator
Creating a web application using Flask ③
Make a model iterator with PySide
When creating a matrix in a list
Creating a web application using Flask ④
[Python] Chapter 03-01 turtle graphics (creating a turtle)
A series of amateur infrastructure engineers touching Django with Docker (2): Creating a model
Creating a simple PowerPoint file with Python
Use a scikit-learn model trained in PySpark
Create a model for your Django schedule
Creating a LINE bot ~ Creating, deploying, and launching ~
Commands for creating a new django project
Sum of variables in a mathematical model
Creating a python virtual environment on Windows
Creating a login screen with Django allauth
Memo for creating a text formatting tool
Creating a data analysis application using Streamlit
Get a reference model using Django Serializer
[Python] Creating a stock price drawdown chart
Creating a shell script to write a diary
Memo about Sphinx Part 1 (Creating a project)
Creating a cholera map for John Snow
Creating a virtual environment in an Anaconda environment
Implement a model with state and behavior
Creating a development environment for machine learning
Implement a Custom User Model in Django
python: Creating a ramen timer (pyttsx3, time)
Try TensorFlow RNN with a basic model
Creating a position estimation model for the Werewolf Intelligence Tournament using machine learning