django database table building process and table structure

Keywords: R Language Database MySQL Django SQL

Catalog

Configure the database

  • In the settings.py file of the Django project, configure database connection information:
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "Your database name",  # You need to create your own database manually
        "USER": "Database username",
        "PASSWORD": "Database password",
        "HOST": "data base IP",
        "POST": 3306
    }
}
  • Write the following code in the _init_ py file under the directory with the same name as the Django project. Tell Django to connect MySQL database using pymysql module:
import pymysql
pymysql.install_as_MySQLdb()
  • Note: A warning appears during database migration
WARNINGS: 
?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'
HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion,
 by escalating warnings into errors. It is strongly recommended you activate it.
  • Add an OPTIONS parameter to the configuration: Django official website interpretation
#Solution 1
OPTIONS: {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"},
        
#Solution II
#To set my.ini of mysql file
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

#Restart mysql(windos system) at the input command
net stop mysql
net start mysql

Create a table structure

  • Example Publishing List

  • Publishing List
from django.db import models

class Publisher(models.Model):
    pid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32, unique=True)
"""
Publisher 
The PID is the id of the publisher and is set as the primary key. The default is the int type primary_key=True field named pid.
Name is the name of the publishing house, and the length of the character is limited to 32. Set the unique=True field to be named
 You can also add fields such as phone, office address, etc. I won't add them here.
"""

class Book(models.Model):
    title = models.CharField(max_length=32)
    pub = models.ForeignKey("Publisher",on_delete=models.CASCADE)
"""
Booklist Design Table Name Book
 Title limits character length 32 for book title
 put is a foreign key model. ForeignKey ("Publisher") associated with the Publisher table on_delete=models.CASCADE to set cascade relationships
"""    
  • Table structure

  • Cascade deletion (set the cascade for the disadvantaged party, the related party deletes, they will delete themselves, delete themselves, but do not affect the other party)

    Delete the Southern Publishing House, and the corresponding diary books of "Big Fat and Little Fat" have also been deleted.

  • Cascade deletion, deletion of books deletion psychology 1500 ask to see the impact of publishing tables?

  • The Structure of Students'Class Schedule

class Class(models.Model):
    cid = models.AutoField(primary_key=True)
    cname = models.CharField(max_length=32, unique=True)
    """
    cid Primary key 
    cname Constrained 32-bit characters,unique=True Constrained uniqueness
    """

class Student(models.Model):
    sid = models.AutoField(primary_key=True)
    s_name = models.CharField(max_length=32,null=False)
    gender = models.CharField(max_length=2,default='male')
    class_id = models.ForeignKey("Class",on_delete=models.CASCADE)
    """
    sid Primary key
    s_name Character 32-bit non-null constraint
    gendef Character 2 is set to male by default
    class Foreign key Association Class surface , Cascade settings
    """

Settings of multi-table gateways

  • Take Publishing House books as an example and add authors
#In order to realize the association of author table with publishing house and Secretary table, the fourth chapter table should be created to set up exercises.

#The first django helps us generate the third table
class Author(models.Model):
    name = models.CharField(max_length=32)
    books = models.ManyToManyField('Book')  # Automatically generate the third table instead of producing fields in the Author table
    """
    name Author's name 32 is a character
    books Book and Author Many-to-many relationship. books yes Author with Book All objects associated. books The function is to
Author and Book Create an intermediate relational object, place it in the third table, and get it according to the intermediate relationship. Book Objects associated in
    """

  • view the database

Self-Creating Association Table Method

class AuthorBook(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    date = models.DateField()
    """
    author Relation Author Cascade settings for authors'external keys
    book Relation Book Cascade Settings of Foreign Keys in Book Sheets
    date Date attributes
    //More fields can be added, which is more troublesome than operation.
    """
#Call method
author_obj = models.Author.objects.create(name=author_name) # Insert only the contents of the book table
author_obj.books.set(books)  # Setting up a multi-to-many relationship between authors and books

Joint use of self-built tables and ManyTo ManyField

class Author(models.Model):
    name = models.CharField(max_length=32)
    books = models.ManyToManyField('Book',through='AuthorBook')  # through='AuthorBook'does not produce fields in the Author table.
//No third table is produced.


class AuthorBook(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)#Foreign key Association Author table cascade settings
    book = models.ForeignKey(Book, on_delete=models.CASCADE)#Cascading Settings for Foreign Key Associated Book Table
    date = models.DateField()#More fields can be set

Posted by peppeto on Wed, 19 Jun 2019 11:36:13 -0700