1. Basic development process
1. Configure the database
2. Define the model class: a model class corresponds to a data table in the database
3. Generate migration files
4. Execute the migration file to generate the data table
5. Use model classes to add, delete, modify and check operations
2. ORM
1 Overview
Convert the object to SQL, then use the data API to execute the SQL and get the execution result. ORM stands for Object-Relational-Mapping.
2. Function
A. Generate table structure according to object type
B. Convert the operations of objects and lists into sql statements
C. Convert the results queried by the sql statement into objects and lists
3. Advantages
Greatly reduces the workload of developers, and does not need to modify the code due to database changes
3. Define the model
1. Relationships between models, attributes, tables, and fields:
A model class corresponds to a table in the database; the attributes defined in the model class correspond to the fields in the model comparison table.
2. Define properties
A. Overview
django determines the following information based on the type of the attribute
the type of field supported by the currently selected database
The default html control to use when rendering the admin form
·Minimum verification at the admin site
B、
Django will add an auto-growing primary key column to the table. Each model can only have one primary key column. If you use an option to set an attribute as the primary key column, Django will no longer generate the default primary key column.
C, attribute naming restrictions
Follow the rules for identifiers
·Consecutive underscores are not allowed due to the way django queries
3. Library
When defining attributes, the field type is required. The field type is defined in the django.db.models.fields directory. For convenience, it is imported into django.db.models
·How to use:
· Import from django.db import models
Create an object of field type through models.Field and assign it to a property
4. Logical deletion
Logical deletion is performed for important data, not physical deletion. The implementation method is to define the isDelete attribute, the type is BooleanField, and the default value is False
5. Field type
·AutoField
An IntegerField that automatically grows according to the actual ID, usually not specified If not specified, a primary key field will be automatically added to the model
·CharField(max_length=character length)
String, the default form style is TextInput
·TextField
Large text fields, generally more than 4000 are used, the default form control is Textarea
·IntegerField
·Integer
·DecimalField(max_digits=None, decimal_places=None)
A decimal floating point number represented using python's Decimal instance
·Parameter Description
·DecimalField.max_digits
·Total number of digits
·DecimalField.decimal_places
· Number of digits after the decimal point
·FloatField
Floating point numbers represented by Python's float instance
·BooleanField
true/false field, the default form control for this field is CheckboxInput
·NullBooleanField
·Support null, true, false three values
·DateField([auto_now=False, auto_now_add=False])
A date represented using Python's datetime.date instance
·Parameter Description
·DateField.auto_now
· Every time the object is saved, this field is automatically set to the current time, for the "last modified" timestamp, it always uses the current date, the default is false
·DateField.auto_now_add
Automatically set the current time when the object is first created, the timestamp used for creation, it always uses the current date, defaults to false
·illustrate
The default form control for this field is a TextInput. Added a JavaScript-written calendar control to the admin site, and a "Today" shortcut button that includes an additional invalid_date error message key
·Notice
auto_now_add, auto_now, and default These settings are mutually exclusive, any combination of them will produce incorrect results
·TimeField
·Use Python's datetime.time instance to represent the time, the parameters are the same as DateField
·DateTimeField
·Use Python's datetime.datetime instance to represent the date and time, the parameters are the same as DateField
·FileField
· A field for uploading files
·ImageField
Inherit all the properties and methods of FileField, but verify the uploaded object to make sure it is a valid image
6. Field options
·Overview
·Through field options, you can implement constraints on fields
· Specified by keyword arguments in the field object
·null
If True, Django will store empty values in the database as NULL, the default value is False
·White person
· If True, the field is allowed to be blank, the default value is False
·Notice
·null is the concept of database category, blank is the category of form validation
·db_column
the name of the field, or the name of the property if not specified
·db_index
If the value is True, an index will be created for this field in the table
·default
·Defaults
·primary_key
If True, the field will become the primary key field of the model
·unique
· If True, this field must have a unique value in the table
7. Relationship
·Classification
·ForeignKey: one-to-many, define the field in the multi-end
·ManyToManyField: many-to-many, define fields in both ends
OneToOneField: One-to-one, define fields in either end
·Use one access to many
·Format
Object.Model class lowercase _set
· Example
grade.students_set
·Access one with one
·Format
Object.Model class lowercase
· Example
·grade.students
access id
·Format
object.property_id
· Example
·student.sgrade_id
8. Meta options
concept:
Define the Mate class in the model class to set the meta information
db_table:
Define the table name, it is recommended to use lowercase letters, the default is the project name (lowercase)_class name (lowercase)
ordering:
The default sort field for objects, used when getting a list of objects.
ordering['id'] : sort in ascending order by id
ordering['-id'] : sort in descending order by id
Using sorting increases database overhead
4. Model members
1. Class attributes
objects: is an object of the Manager class, which is used to interact with the database.
When defining a model class, if no manager is defined, a manager named objects is created by default.
2. Custom Model Manager
Format: custom name=models.Manager()
When a manager is defined for a model, Django will no longer generate an objects model manager for the model.
3. Custom Manager Manager class
Overview: A model manager is an interface for Django's models to interact with the database. A model can have multiple managers.
Role: Add additional methods to the manager class; modify the original query set returned by the manager - override the get_queryset() method.
Eg: in the models.py file
class StudentsManager(models.Manager):
def get_queryset(self):
return super(StudentsManager,self).get_queryset().filter(isDelete= False )# Take out the data that satisfies the isDelete= False condition
5. Create objects
1. Purpose
Add data to the database. When an object is created, Django will not read or write to the database. When the save() method is called, it will interact with the database and save the object to the database.
2. Pay attention
The __init__ method is already used in the parent class models.Model and cannot be used in custom models
3. Create method
A. define a class
Write the following code in models.py:
class Students (models.Model): #Create data table sname=models.CharField(max_length=20) #Define field sage=models.IntegerField(3 ) sgender=models.CharField(max_length=20) @classmethod #Custom create object def createStudent(cls,name,age,gengder): stu=cls(sname=name,sage=age,sgender=gengder) return stu
In views.py file write like this;
from .models import Students def addstudent(requset): stu =Students.createStudent( ' tom ' ,34, ' tom is good ! ' ) #The parameter order corresponds to the parameter order in cls when creating a class stu.save() return render(requset,'addstudent.html')
B. Create a class in the model manager
class StudentsManager(models.Manager): def creatStudent(self,name,age,content): stu=self.model() stu.sname=name stu.sage=age stu.scontent = content return stu
6. Model query
1 Overview
A queryset, which represents a collection of objects fetched from the database.
A filter is a function that restricts queryset results based on given parameters. A queryset can have multiple filters.
From the SQL point of view, the query set is equivalent to the select statement, and the filter is equivalent to the where condition.
2. Query set
A. Overview
Calling the filter method on the manager returns the queryset. The query set is filtered by the filter method and returns a new query set, so it can be written as a chain call.
B. Lazy execution
Creating a query set will not bring any data access, until the data is called, the database will not be accessed
C. Direct access to the database
Iterate, serialize, use with if
D. filter
A filter, a method that returns a queryset is called a filter.
all(): returns all data
filter():
Returns matching data.
filter('key' = 'value'): The key is the field name in the data table and the value is the condition. Returns the data that meets the condition
filter('key' = 'value', 'key' = 'value'): returns data that satisfies both conditions
filter('key' = 'value') . filter('key' = 'value'): same as above
exclude(): filter out data that meets the conditions
order_by('field name'): sort by a field
values(): A piece of data is an object (dictionary class), returning a list
E. Return a single data
get(): Returns an object that satisfies the condition. Note: If no matching object is found, a "ModelClass.DoesNotExist" exception will be raised; if multiple objects are found, a "ModelClass.MultipleObjectsReturned" exception will be raised.
count(): Returns the number of objects in the current query set.
first(): Returns the first object in the queryset
last(): Returns the last object in the queryset
exists(): Determines whether there is data in the query set, and returns True if there is data
F. Restricted query set
The query set returns a list, which can be limited using the subscript method, which is equivalent to the limit statement in SQL.
eg:
studentsList=students.objects.all()[0:5]
Note: Subscripts cannot be negative
G. Cache of query sets
Each query set contains a cache to minimize access to the database; in a newly created query set, the cache is empty for the first time, and the first time the data set query is evaluated, data caching will occur, and Django will query the data. Make a cache and return the query structure, and subsequent queries directly use the cache of the query set.
F. Field query
Overview:
The where statement in SQL is implemented as a parameter of the methods filter(), exclude(), and get().
grammar:
attribute name__comparison operator=value
Foreign key:
attribute_id
Escape:
Comparison operator:
exact: judgment, case-sensitive
contains: whether to contain, case sensitive
eg:views.py
def studentsearch(request): studentList=Students.objects.filter(sname_contains='grandchild')#Query the value of 'grandchild' in the sname field value in the Student data table return rander(request,'news.html',{"students":studentList})
startswith(value), endswith(value): starts or ends with value, case sensitive
eg:views.py
def studentsearch(request): studentList=Students.objects.filter(sname_startswith='grandchild') #Query the value starting with 'grandchild' in the sname field value in the Student data table return rander(request,'news.html',{"students":studentList})
Note: The above four are preceded by i, which means case insensitive. iexact, icontains, istartswith, iendswith.
isnull、isnotnull:
Determine if it is empty. Consistent with the above methods: attribute name __isnull=False)
in:
Is it included.
gt: greater than
gte: greater than or equal to
lt: less than
lte: less than or equal to
year: year
month: month
day: day
week_day
minute: minute
second: seconds
G. Quick query
PK: represents the primary key
H. Aggregate function
Avg(): take the average
Count(): Returns the number of data
Max(): Returns the maximum value of the field
Min(): Returns the minimum value of the field
Sun(): Returns the sum of the field
I: Cross-Relational Query
Process join queries. Syntax: model class name __ attribute name __ comparison operator.
eg: Returns which class the data with the three words "Sun Honglei" in the description belongs to
grade=Grades.objects.filter(students__scontend__contains='Sun Honglei')
Grades: Grade data table, this table has a class field
students: student data table, which has a description field "scontend"
contains: comparison operator, contains
J, F object
Using the attributes of model A to compare with the attributes of model B is actually a comparison of two values of a piece of data.
F objects support arithmetic operations.
eg: views.py to take out the data that the number of girls is more than the number of boys
from django.db.models import F def grades(request): #Remove data with more girls than boys g=Grades.objects.filter(ggirlnum__gt=F('gboynum')) #Get the data where the number of girls is greater than the number of boys plus 20 gb =Grades.objects.filter(ggirlnum__gt=F( ' gboynum ' +20 )) print(g) print(g)
Grades: Grade Data Sheet
ggirlnum: field, the number of girls
gt: comparison operator, greater than
gboynum: field, the number of boys
K, Q object
make or inquire.
eg:views.py
from django.db.models import Q def grades(request): #Remove all values with primary key value less than 3 or sage greater than 18 s =Students.objects.filter(Q(PK__lte=3)|Q(sage__gt=18)) # print (s)
Seven, the addition of foreign keys
models.py
class A(models.Model): title = models.CharField(max_length=20) class B(models.Model): bname = models.CharField(max_length=20) fk = models.ForeignKey(A, on_delete=models.DO_NOTHING)
views.py
from .models import * # 方法一 B.objects.creat(bname='test', fk=A.object.get(id=1)) # 方法二 B.objects.creat(bname='test', fk_id=1)