Django's database configuration, generation (creation) process, writing data, viewing data learning process records

01- Configure database information

Write the configuration information of the following database in the file: "E:\Python_project\P_001\myshop-test\myshop\myshop\settings.py":

DATABASES = {
    
    
    'default': {
    
    
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'shop-test',
        'USER': 'shop-test',
        'PASSWORD': 'Aa_123456',
        'HOST': 'localhost',
        'PORT': '3306',
        # 取消外键约束,否则多对多模型迁移报django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')
        'OPTIONS': {
    
    
            "init_command": "SET foreign_key_checks = 0;",
            'charset': 'utf8'
        },
    }
}

insert image description here

The above code is easier to understand, that is, django.db.backends.mysqlsome explanations for the statement:
In Django, 'django.db.backends.mysql'it is the path of a database backend engine, which is used to specify the use of MySQL as the backend of the database. A database backend engine is the component Django uses to interact with different types of databases. It provides support for database connection, query and data manipulation.

Django supports multiple database backend engines, such as MySQL, PostgreSQL, SQLite, etc. By setting 'ENGINE'options, you can specify the specific backend engine to use. In this example, 'django.db.backends.mysql'MySQL is used as the database backend engine.

By choosing different back-end engines, you can use different types of databases to store and retrieve data, and the ORM (object-relational mapping) function provided by Django will provide you with a consistent data access interface, no matter what kind of database you use side engine. In this way, you can easily switch and manage different types of databases without changing a lot of code.

In the above configuration, the foreign key constraint is also canceled, otherwise the following prompt will appear during the migration of the "many-to-many" model relationship:

django.db.utils.IntegrityError:(1215, 'Cannot add foreign key constraint')

If you need to configure the database statement (*) corresponding to the output, you need to write the following configuration statement in "E:\Python_project\P_001\myshop-test\myshop\myshop\settings.py":

LOGGING = {
    
    
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
    
    
        'console':{
    
    
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
    
    
        'django.db.backends': {
    
    
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}

What does the statement "'disable_existing_loggers': False," in the above log output configuration code mean?
A: In Django's logging configuration, 'disable_existing_loggers'is a boolean option that specifies whether to disable an existing logger. What it does is control whether existing loggers are preserved, rather than replacing them entirely.

When 'disable_existing_loggers'set Trueto , existing loggers are disabled. This means that new loggers defined in the logging configuration will take effect and existing loggers will be ignored. This is often used to completely replace the default Django logging configuration.

When 'disable_existing_loggers'set Falseto , keep the existing logger. That means, new loggers will work with existing ones, not replace them. This is typically used to extend the default Django logging configuration, adding additional loggers or modifying the behavior of existing loggers.

In a given configure statement, 'disable_existing_loggers': Falseindicates that existing loggers are not disabled, but are preserved, and new loggers are added to the existing set of loggers. This ensures that the existing Django database backend logger still works and sends log output to the console.

Statement: 'propagate': True, what does it mean?
Answer: In Django's logging configuration, 'propagate'is a boolean option that specifies whether log messages should be propagated to higher-level loggers.

When 'propagate'set Trueto , log messages will be propagated to the parent logger. This means that if the current logger cannot process a log message, it will pass the message to its parent logger so it can be processed or passed to a higher level logger. Propagation enables log messages to be delivered and processed throughout the logger hierarchy.

When 'propagate'set Falseto , log messages are not propagated to parent loggers. If the current logger cannot process a log message, the message will be silently discarded and not passed to a higher level logger.

In a given configuration statement, 'propagate': Trueindicates that log messages will be propagated to parent loggers. This means that if 'django.db.backends'a logger cannot process a log message, it will be passed to a higher level logger for processing. By setting to True, you ensure that database backend log messages are propagated throughout the logger hierarchy to be processed or logged as needed.

02- Install Python's MySQL database driver mysqlclient

The installation command is as follows ( be careful to turn off the proxy tool before installation ):

pip install -i https://mirrors.aliyun.com/pypi/simple mysqlclient

After the installation is successful, as shown in the figure below:
insert image description here

03- Install Mysql and start Mysql

Here, you can use the small skin panel to install Mysql, of course, you can also go to the official website of Mysql to download the installation package and install it.
If you are using a small skin panel to install Mysql, you can refer to my previous blog post:
https://blog.csdn.net/wenhao_ir/article/details/126170178
Start the Mysql service after installation:
insert image description here
then switch to the database, press The information in the configuration code in step 01 creates a new database:
insert image description here
insert image description here
insert image description here
insert image description here

04-Define Django's database model (define data table-write models.py file)

Write the following content in ""E:\Python_project\P_001\myshop-test\myshop\app1\models.py"":

from django.db import models

# Create your models here.


class User(models.Model):
    username = models.CharField(max_length=50)
    email = models.EmailField(unique=True)
    # 其他字段...

    def __str__(self):
        return self.username

    

05-Generate the database according to the configuration of the data (execute the migration command)

Why is database generation called migration in Django? Please refer to another blog post I wrote, https://blog.csdn.net/wenhao_ir/article/details/131544152

05-01-Generate migration execution file

Generate the "migration execution file" with the following commands:

CD E:\Python_project\P_001\myshop-test\myshop\
E:
manage.py makemigrations

If the above command is normal, the running result is as follows:
insert image description here
Open the file: "E:\Python_project\P_001\myshop-test\myshop\app1\migrations\0001_initial.py", you
can see that the file contains the creation statement of the current model, 0001_initial. The content of py is as follows:

# Generated by Django 3.2.10 on 2023-07-05 13:32

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('username', models.CharField(max_length=50)),
                ('email', models.EmailField(max_length=254, unique=True)),
            ],
        ),
    ]

05-02 - Execute Database Model Migration

Continuing from the previous step, use the following three statements to implement the migration of the database model.

CD E:\Python_project\P_001\myshop-test\myshop\
E:
manage.py migrate

insert image description here

06-View database

You can use the tool "opendbviewer" to view the database.
The Baidu network disk download link of this tool is as follows:
https://pan.baidu.com/s/19VxBiWHPmuJ_ApVgI3bqhA?pwd=e1te
After the installation is complete, you can view the database after connecting to the database~As shown in the figure below:
insert image description here

07-Write data to the database and view the data

Create a new file sql_test.py under the path: E:\Python_project\P_001\myshop-test\myshop\ (equal to manage.py):
insert image description here
Then write the following code:

import os
import django

# 设置Dango运行时需要的环境变量DJANGO_SETTINGS_MODULE
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings')

# 加载Django的设置
django.setup()

# 导入模型,注意必须在加载完Django的设置后下面的这句导入模型语句才能被正确执行
from app1.models import User

# 创建一个用户
user = User(username='john', email='[email protected]')
user.save()

Explanation of the statement os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings'):
When we run the Django project in Python, we need to tell Django the project settings (settings) to use. These settings include database configuration, application listings, static file paths, and more.
How to tell Django project settings (settings)? Tell via the environment variable DJANGO_SETTINGS_MODULE.
Here, os.environ.setdefault(key, value)is the method to set an environment variable. It accepts two parameters: keyis the name of the environment variable to be set, valueand is the value to be set for the environment variable.
'DJANGO_SETTINGS_MODULE'As I have just said, its function 'myshop.settings'is to set the value of the variable, indicating that Django should use the files myshopin the project settings.pyas the project settings.

Execute the above code to write data to the database. After execution, we will look at the records of the database:
insert image description here
we find that there is already a new record in the table User of the database shop-test.

Let's run the following code again, and write a new record:

import os
import django

# 设置Dango运行时需要的环境变量DJANGO_SETTINGS_MODULE
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings')

# 加载Django的设置
django.setup()

# 导入模型
from app1.models import User

# 创建一个用户
user = User(username='suwenhao', email='2487872782.com')
user.save()

After the operation is complete, a new record is added to the database:
insert image description here

Attach complete code

https://pan.baidu.com/s/1mmNZyyV9lrmsTc0s1GvW1Q?pwd=i6g9

Guess you like

Origin blog.csdn.net/wenhao_ir/article/details/131558124