ORM

Class mapping to table class attributes mapping to object instances of table field classes mapping to a row of records

= = = =

  1. Avoid writing SQL statements and use object-oriented methods to operate the database, which is easier to use.
  2. Decouple the project from the database and switch the database with a simple configuration.

= = = = shortcomings

  1. For complex services, operations are complicated
  2. Performance is not as efficient as SQL

Djangos config database

In the configuration file settings.py

DATABASES = {
	"default": {"ENGINE":"django.db.backends.mysql"."HOST":"localhost"."PORT":"3306"."USER":"lauf"."PASSWORD":"lauf123"."NAME":"my_db"."CHARSET":"utf8",}}Copy the code

Sudo pip3 install mysqlClient sudo pip3 install mysqlClient sudo pip3 install mysqlClient sudo pip3 install mysqlClient

sudo apt-get install libmysqlclient-dev
sudo apt-get install default-libmysqlclient-dev
sudo apt-get install python3-dev

Check whether the installation is successful
sudo apt list --installed | grep -E "libmysqlclient-dev|python3-dev"
Copy the code

Check whether PIP3 is installed successfully (mysqlClient)

pip3 freeze | grep -i "mysqlclient" 
Copy the code

Create a model class

Here, in the User application, I show you how to create a model class

# Create the user application in the project directory
python3 manage.py startapp user
Install settings.py
INSTALLED_APPS = [
	...,
	"user",]# Define the model class user>models.py for the application
from django.db import models
class User(models.Model) :
	username = models.CharField("Name",max_length=50,primary_key=True)Max_length must be given
	password = models.CharField("Password",max_length=50,null=False)
	score = models.DecimalField("Score",max_digits=4,decimal_places=2) # decimal position
	is_delete = models.BooleanField("Delete or not",default=False)
	created_time = models.DateTimeField("Registration Time",auto_now_add=True)
	updated_time = models.DateTimeField("Update Time",auto_now=True)
	def __str__(self) :
		""" The information to display when printing an object """
		return self.username
	class Meta:
		db_table = "user_table" Alter table name alter table name

Migrate the model classes to the database
python3 manage.py makemigrations
python3 manage.py migrate
Copy the code

When no primary key is specified, Django automatically creates an ID as the primary key.

== Practice adding a hobby field == to the user table

# In the model class, add class attributes
hobby = models.CharField("Hobby",max_length=50,default="") You must give a default value in order to avoid errors in previous data without this field

# Migrate to database
Copy the code

The field type of the model class

  1. BooleanField()

Corresponding to tinyint in the database, 0/1; Django to True/False

  1. CharField()

Max_length must be specified for the vARCHAR in the database

  1. DateField()

Date, auto_now = True, update time auto_now_add = True, first insert time default give a default value

  1. DateTimeField() uses the same method as DateField()
  2. FloatField() corresponds to a double in the database
  3. DecimalField() Specifies the exact decimal number corresponding to the database decimal required parameters: max_digits=5 total digits, decimal_Places =2 decimal position
  4. EmailField() corresponds to database VARCHAR
  5. IntegerField() –>int
  6. ImageField() –> vARCHar (100) storage path
  7. TextField –>longtext longtext

Constraints on class attributes

Primary_key, bool, indicates whether the class attribute is the primary key

Blank,bool: indicates whether the field is empty. Admin can not write the field in the background

Null,bool indicates whether the column can be null

Default: indicates the default value

Db_index,bool Indicates whether to set the index in this column

Unique,bool whether the value of this column is unique, unique index

Db_column Specifies the column name. By default, class attributes are used as column names

Verbose_name, the field name displayed in the background

practice

Create a Book model class with the following attributes: Title, title, character type, Max length 50, and value unique price, exact decimal, Max 5 digits, one decimal, publish, publisher, character type, Max length 50, cannot be null when printing an object, output the title, and change the table name book_table\

Note: Every time a model class is modified, it is migrated; If migration fails, delete migration files in the migrations directory, except __init.__py, delete the library, rebuild the library, and migrate again

Djangos model Class 2