current position:Home>Django model class 1

Django model class 1

2022-01-31 05:33:08 laufing

ORM

 Insert picture description here

Class mapping to table
Class attributes are mapped to table fields
The object instance of the class is mapped to a row of records

== advantage ==

  1. Avoid writing SQL sentence , Use an object-oriented way to operate the database , Easy to use .
  2. Decouple the project from the database , Switching databases requires simple configuration .

== shortcoming ==

  1. For complex business , The operation is complicated
  2. No performance SQL Efficient

Django Configuration database

In profile settings.py in

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

}
 Copy code 

== Be careful ==
django Connect mysql Use python Of mysqlclient library , Need to install :sudo pip3 install mysqlclient If an error mysql_config, You have in linux The following dependencies are installed in the system environment :

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 code 

see pip3 Is the installation successful (mysqlclient)

pip3 freeze | grep -i "mysqlclient" 
 Copy code 

Create model classes

Here it is user Application , Show how to create a model class

# Under the project directory , establish user application 
python3 manage.py startapp user
# Install application  settings.py
INSTALLED_APPS = [
	...,
	"user",
]
# Define model classes for applications  user>models.py
from django.db import models
class User(models.Model):
	username = models.CharField(" full name ",max_length=50,primary_key=True)# Must give max_length
	password = models.CharField(" password ",max_length=50,null=False)
	score = models.DecimalField(" fraction ",max_digits=4,decimal_places=2) # Decimal place 
	is_delete = models.BooleanField(" Whether or not to delete ",default=False)
	created_time = models.DateTimeField(" Registration time ",auto_now_add=True)
	updated_time = models.DateTimeField(" Update time ",auto_now=True)
	def __str__(self):
		""" When printing objects , Information displayed """
		return self.username
	class Meta:
		db_table = "user_table" # Change table name 

# Migrate model classes , To database 
python3 manage.py makemigrations
python3 manage.py migrate
 Copy code 

When no primary key is specified ,Django Automatically create a id A primary key .

  == Practice for user Table add a hobby Field ==

# In the model class , Add class attribute 
hobby = models.CharField(" hobby ",max_length=50,default="") # Prevent previous data from reporting errors without this field , We must give one default

# Migrate to database  
 Copy code 

Field type of model class

  1. BooleanField()

Corresponding to tinyint,0/1; Django In Chinese, it means True/False

  1. CharField()

Corresponding to varchar, Must specify max_length

  1. DateField()

Corresponding to date, Parameters ,auto_now = True, Update time auto_now_add = True, First insertion time default Give a default value

  1. DateTimeField() Use the same as DateField()
  2. FloatField() Corresponding to double
  3. DecimalField() Exact decimal , Corresponding database decimal Required parameters :max_digits=5 The total number of digits ,decimal_places=2 Decimal place
  4. EmailField() Corresponding database varchar
  5. IntegerField() -->int
  6. ImageField() --->varchar(100) Storage path
  7. TextField --->longtext Long text

Constraints on class properties

primary_key, bool, Whether the class attribute is a primary key

blank,bool, Is it empty ,admin Fields that can not be written during background management

null,bool, Whether the column can be null Null value

default, The default value is

db_index,bool, Whether to set index in this column

unique,bool, Whether the value of this column is unique , unique index

db_column Column name , By default, the class attribute is used as the column name

verbose_name, Field name displayed in the background

practice

Create a Book Model class , Class properties are as follows :
title, Title , Character type , Maximum length 50, And the value is unique
price, Price , Exact decimal , Maximum 5 digit , One decimal place
publish, Press. , Character type , Maximum length 50, Not for null
When printing objects , Output the title of the book , And modify the table name to book_table\

Be careful : Every time you modify the model class , All have to migrate ; Migration failed , Delete migrations Migration files in the directory , except __init.__py, Delete Library , Rebuild Library , Re migrate

Last one :Django Application

copyright notice
author[laufing],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201310533059366.html

Random recommended