SoFunction
Updated on 2024-11-13

Python Django ORM and Modeling Explained

I. Environmental preparedness:

matrix

The docker environment is as follows:

在这里插入图片描述

2. Install the mariadb database

Run the following command

docker run --d --name [container name] -v test:/var/lib/mysql -p 3306:3306 --env MARIADB_USER=[username] --env MARIADB_PASSWORD=[user password] --env MARIADB_ROOT_ PASSWORD=[root user password] --env MARIADB_DATABASE=[library name] mariadb:latest

Parameter details:

  • name: Startup Container Setting the Container Name
  • v: Set the container directory /var/lib/mysql to map to the local directory test
  • p: Set the container's port 3306 to map to host port 3306
  • env: Setting environment variables database related information
  • d: Runs container mariadb in the background and returns the container id
  • mariadb:latest: Launch the latest version of the image

Wait for the command to finish running and then you can view the started containers:

在这里插入图片描述

navicat connection test:

在这里插入图片描述

Created database.

在这里插入图片描述

II. ORM

synopsis

orm (object relational mapping) object-relational mapping , object-oriented way to describe the database , the database operation , to achieve the database without writing sql statements can be added, deleted, changed and checked a technology , but orm the bottom or through the native sql to achieve .

在这里插入图片描述

shown above, and the objects of the model are equivalent to the data in the table.

Configuration Database

You need to install the mysql driver before configuring the database. This environment uses the mariadb database to install the driver:

pip install mysqlclient

Configuration information can be added after the installation is complete in the following two ways:

The first way:

Configured directly in:

DATABASES = {
    'default': {
        'ENGINE': '',
        'NAME': 'library name',
        'USER': 'user ID',
        'PASSWORD': 'user password',
        'HOST': 'domain name',
        'PORT': 'port number'
    }
}

The second way:

Add a configuration file:

A new configuration file directory is created in the root directory and a configuration file is created to fill in the database information:

# 
[client]
database = library name
user = user ID
password = user password
host = domain name
port = ports

center

DATABASES = {
    'default': {
        'ENGINE': '',
        'OPTIONS': {
            'read_default_file': str(BASE_DIR / [Configuration file path])
        }
    }
}

III. Model design

Models in django accurately and uniquely describe the data, and each model is a python class that inherits from the class. Each familiar in the model class is a field in the database, and django provides an automatically generated API for accessing the database.

1. Create a model

The models for each application are written under the file, as shown here, and the models module is automatically introduced when the project is created.

在这里插入图片描述

Create a student table as an example:

from  import models


# Create your models here.

class Stutent():
    """
    Student Table
    """
    name = ('Student Name', max_length=200, unique=True, help_text='Student Name')
    sex = ('Gender', max_length=48, help_text='Gender')
    hobby = ('Hobbies', max_length=200, null=True, blank=True, help_text='Hobbies')
    create_time = ('Creation time', auto_now_add=True, help_text='Creation time')

    class Meta:
        """
        Metadata.
        """
        db_table = 'student'  # Specify the current model created, without the default current model name Student.
        verbose_name = 'Student Information Sheet'  # Note
        verbose_name_plural = verbose_name  # Designated as plural
        ordering = ['-create_time'] # Sort in reverse chronological order using creation time, without - for positive order

CharField   The character type represents the databaseVARCHAR
DateTimeField  Date Field Type
IntegerField  Integer field types
FloatField  Numeric field types
DecimalField  High Precision Field Types
max_length  Length limitation of data,When using theCharFieldhour,This field must be passed,Otherwise, it's an error.
unique because ofTrue  Represents field uniqueness
null because ofTrue  代表可以because of空
blank because ofTrue  Do not validate this field
SmallIntegerField small integer
auto_now_add  combiningDateTimeField utilization,默认because of当前hour间

2. Table relationships

Table relationships in Django can be expressed in the following way

one-to-many relationship:()        Created on the side of more
many-to-many relationship:()   Random Table Creation
one-to-one relationship:()     Random Table Creation

Continue to create student class models:

class Class():
    name = ('Class name', max_length=200)
    class_num = ('Classes', unique=True, help_text='Class number')
    student = (Stutent, on_delete=)  # set foreign key, on_delete cascade delete

IV. Model applications

The application needs to be de-registered in INSTALLED_APPS in the settings file before the database migration.

在这里插入图片描述

Step one:

Generate data migration records
python  makemigrations projects

Running the command generates a migration log file in the migrations directory and the id is automatically created as follows:

在这里插入图片描述

The underlying django is implemented in sql, view the sql commands generated by executing the migration as follows:

python  sqlmigrate projects 0001

在这里插入图片描述

Step two:

Perform migration

python  migrate 

The database generates table information after executing the command

在这里插入图片描述

summarize

That's all for this post, I hope it helped you and I hope you'll check back for more from me!