【英文】Django项目中连接Mysql

Preface

Django project connecting to Mysql learning notes

Download dependencies

  • Install Mysql driver
1
pip install pymysql

Modify global configuration

  • Change the DATABASES configuration in the global configuration from the default sqlite3 configuration to the mysql configuration

ENGINE: Database type
HOST: Access address, leave it empty for 127.0.0.1 by default
PORT: Port number
USER: Login username
PASSWORD: Login password
NAME: Name of the database to connect to

<project_name>/<project_name>/settings.py
1
2
3
4
5
6
7
8
9
10
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '',
'PORT': '3306',
'USER': '',
'PASSWORD': '',
'NAME': '',
}
}

Initialize Mysql driver

<project_name>/<project_name>/__init__.py
1
2
3
import pymysql

pymysql.install_as_MySQLdb()

Creating and Modifying Table Structure

Add a Mysql data table mapping in a Module

  • Map Python class to Mysql data table
    • <app__name>_class_name maps to Mysql data table name
    • The variables defined in the class map to the fields in the Mysql data table

Field types

CharField: String type
TextField: Text type
EmailField: Email format string
UrlField: URL format string
BooleanField: Boolean type
NullBooleanField: Nullable boolean type
IntegerField: Integer type, value range [-2147483648,2147483647]
SmallIntegerField: Short integer type [-32768,32767]
BigIntegerField: Long integer type
PositiveIntegerField: Positive integer type, value range [0,2147483647]
PositiveSmallIntegerField: Short positive integer type, value range [0,32767]
FloatField: Floating point type
DecimalField: Decimal
DateField: Date type, such as YYYY-MM-DD
DateTimeField: Date and time type, such as YYYY-MM-DD hh:mm:ss
TimeField: Time type, such as hh:mm:ss
ImageField: Image type, used to store image format files
FileField: File type, used to store files in any format

Attributes

Attributes that apply to the DecimalField field type

max_digits=<num>: Maximum number of digits allowed in the number
decimal_places=<num>: Number of decimal places stored

Attributes that apply to the ImageField field type

width_field=<num>: Image width
height_field=<num>: Image height

Attributes that apply to the ImageField and FileField field types

upload_to=<src>: Local path for file upload

Attributes that apply to the DateField, DateTimeField, and TimeField field types

auto_now: Automatically add the current time as the default value
auto_now_add: Automatically add the current time as the default value when created for the first time

Attributes that apply to any field type

blank=True: Whether it can be an empty value
null=True: Whether the value can be set to null, usually for the purpose of matching the on_delete attribute
primary=True: Whether it is a primary key
max_length=<num>: Maximum length
default=<value>: Default value
verbose_name=<name>: Name displayed in the admin of the backend management system
db_column=<name>: Database column name
unique=True: Whether it is a unique index, a unique index does not allow duplicates
db_index=True: Whether it is a regular index, a regular index allows duplicates

<project_name>/<app_name>/models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from django.db import models

class User(models.Model):
If not specified, the id will be generated automatically
name = models.CharField(max_length=5, blank=False)
age = models.SmallIntegerField(default=0)
phone = models.CharField(max_length=11, db_index=True, blank=True, default='')
email = models.EmailField(blank=True, default='')
info = models.TextField()
create_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)
Define a unique composite index, a unique index does not allow duplicates
unique.together = []
Define a regular composite index, a regular index allows duplicates
index.together = []

Define a composite index

<project_name>/<app_name>/models.py
1
2
3
4
5
6
7
8
9
10
from django.db import models

class User(models.Model):
If not specified, the id will be generated automatically
name = models.CharField(max_length=5, blank=False)
age = models.SmallIntegerField(default=0)
phone = models.SmallIntegerField(db_index=True, blank=True, default='')
Define a composite index
class Meta:
index_together = ['name', 'phone']

Fields for multiple table association

relate_name="": Customizable name for the current field, if not specified, the Python variable name is used as the field name by default

<project_name>/<app_name>/models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from django.db import models

class User(models.Model):
id = model.IntegerField(primary=True)
name = models.CharField(max_length=5, blank=False)

class OneToOne(model.Model):
id = model.IntegerField(primary=True)
user = model.OneToOneField(User, blank=True, null=True, on_delete=models.SET_NULL)

class OneToMany(model.Model):
id = model.IntegerField(primary=True)
user = model.ForeignKey(User, relate_name="user", blank=True, null=True, on_delete=models.SET_NULL)

class MonyToMont(model.Model):
id = model.IntegerField(primary=True)
user = model.ManyToManyField(User, relate_name="user")

Update Mysql data table structure

  1. Generate script: After defining the mapping, execute the command python manage.py makemigrations