Django It provides good support for all kinds of databases ,Django For these databases to provide a unified call API, Different databases can be selected according to different business needs .
To learn more , Please visit : https://www.emperinter.info/2022/05/29/django-models/
ORM
summary
object - mapping - Model
Mission
Generate table structure based on object type
Put the object 、 The operation of the list is converted to sql sentence
take SQL The result of a statement query is converted to an object 、 list
advantage
Greatly reduces the workload of developers , There is no need to change the code due to changes in the database
technological process
Configuration database
stay __init__.py Add selected database to file Package.
stay settings.py Modify the database configuration in the file .
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'sunck', # Database name
'USER': 'sunk', # Database user name
'PASSWORD': 'sunk', # Database password
'HOST': 'localhost', # Database host
'PORT': '3306', # Database port
}
}
stay models.py Add model class
A model class corresponds to a table in the database
Defining models
Model 、 attribute 、 surface 、 Relationship between fields
A model class corresponds to a table in the database
Attributes defined in the model class , Corresponding to the fields in the model cross reference table
Defining attributes
summary
Django Determine the following information based on the type of attribute
The currently selected database supports the type of field
The default... Used when rendering management forms html Control
Minimal validation at the management site
Django Automatically added primary key columns will be added to the table , Each model can only have one primary key column , If you use the option to set a property as the primary key column , be Django No more default primary key columns will be generated .
Property naming restrictions
It can't be Python Reserved keywords for ( Follow identifier naming rules )
because Django Query mode of , Consecutive underscores are not allowed
library
When defining properties , Field type required , Field types are defined django.db.modles.fields Under the table of contents , For ease of use , Be imported into django.db.modles in
Usage mode :
Import from django.db import models
adopt modles.Field Create an object of field type , Assign to property
Logical deletion
For important data Logical deletion , Can't do Physical delete , The implementation method is to define isDelete attribute , The type is BooleanField, The default value is False.
Field type
Field type
explain
AutoField One is based on reality ID Automatic growth IntergerField, Usually... Is not specified , If you do not specify a primary key field, it will be automatically added to the model CharField(max_length= Character length ) character string , The default form style is TextInputTextField Big text fields , Generally more than 4000 Byte usage , The default form control is textAreaIntegerField Integers DecimalFiled(max_digits=None,decimal_places=None) Use Python Of Decimal The decimal floating point number represented by the instance ,max_digits Represents the total number of digits ,decimal_places The number of digits after the decimal point .[[ Precise floating point operations -Decimal]]FloatField use Python Of Float Instance to represent the floating-point number BooleanFieldtrue/false Field , The default form control for this field is CheckboxInputNullBolleanField Support null、true、false Three values DateField([auto_now=False,auto_now_add=False]) Use Python Of Datetime.date The date represented by the instance ,auto_now Indicates that the object saved each time is , Automatically sets this field to the current time , be used for “ Last revision ” The timestamp , It always uses the current date , The default is False.auto_now_add Indicates that the current time is automatically set when the object is first created , Timestamp used to create , It always uses the current time , The default is False. explain : By default, this field is a TextField, Added a... In the administrator site JavaScript Write calendar control , And a “Today” Shortcut buttons , Contains an additional invalid_date Error message key . Be careful :auto_now_add、auto_now、defalut These settings are mutually exclusive , Any combination between them will have the wrong result .TimeField Use Python Of datetime,datetime The date and time represented by the instance , The parameters are the same as DateFieldFiledField A field for uploading files ImageField Inherited FileField All properties and methods of , But check the uploaded object , Make sure it is an effective image
Field options ( Field parameters )
summary :
Through field options , You can implement constraints on fields
The field object is specified by keyword parameters
null
If True,Django Set null value to NULL Store in database , The default is False
blanke
If True, Then the field can be blank , The default value is False
Be careful :
null It's the concept of database category ,blank It's part of the form validation category
db_column
Name of field , If not specified , Then use the name of the attribute
db_index
If the value is True, The index for this field will be created in the table
defalut
The default value is
primary_key
if True, Then this field will become the primary key field of the model
unique
if True, Then the value of this field must be unique
Relationship
classification
ForeignKey: One to many , Define a field in a multi terminal
ManyToManyField: Many to many , Define the field at both ends
OneToOneField: one-on-one , Define the field at either end .
Use one to access more :
Format : object . Model class lowercase _set
Example :grade.students_set
Use one to access one :
Format : object . Model class lowercase
Example :grade.students
visit id:
Format : object . attribute _id
Example :student.sgrade_id
Create model classes
To learn more , Please visit : https://www.emperinter.info/2022/05/29/django-models/