I'm making a blog using django in python. When setting the table in models.py I want to create a table that has a parent-child relationship like Category> Article.
To link each table Use the variables that exist in each table. Set the variable specified at that time as foreign_key.
The article posted on the blog contains the following classes and data. In the post class id,title,cantent,created_at,category At that time, create a separate category class and id,name,created_at It is composed of.
If you decide the data type and drop them in the code,
class Category(models.Model):
name = models.CharField('Category name',max_length=255)
created_at = models.DateTimeField('date',default=timezone.now)
class Day(models.Model):
title = models.CharField('title',max_length=200)
text = models.TextField('Text')
date = models.DateTimeField('date',default=timezone.now)
category = models.ForeignKey(Category,verbose_name='category',on_delete=models.PROTECT)
Assigned to the category instance of the Day class is the product of models multiplied by the ForeignKey function. At that time, you can take category as the first argument and change the name of the model to any one with verbose_name. And by assigning the PROTECT function to on_delete, even when the deletion process is performed by the category class, the deletion will not be performed as long as the post class exists (the posted article will not be deleted even if the category is deleted).
By using the ForeignKey function The setting source is the parent table, and the referenced side is the small table and is associated.
Reference article ForeignKey:https://www.sejuku.net/blog/54072 verbose_name:https://codor.co.jp/django/how-to-use-verbose-name
Recommended Posts