Some common query operations in Python model
This article introduces the knowledge of "some common query operations in the Python model". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Catalogue
Some query operations in the model:
1. Aggregate query: aggregate () is a termination clause of QuerySet
2.Q query: if you need to execute more complex queries (such as OR statements)
3.F query: (query is a whole column of data! )
4. Grouping query
4.1 one-to-many relationship
4.2 many-to-many relationship
Some query operations in the model: 1. Aggregate query: aggregate () is a termination clause of QuerySet
It returns a dictionary containing some key-value pairs
From movie.models import Userfrom django.db.models import Count, Avg, Max, Min, Sumdef test_info (request): # aggregate query # to find the average age in User the default data format returned is a dictionary, where the key name is age__avg, and the value is the average of the specified field. Rs = User.objects.all (). Aggregate (Avg ("age")) # specifies a name by specifying the key name of the dictionary as follows. Rs = User.objects.all (). Aggregate (age=Avg ("age")) # average, maximum, minimum, summation rs = User.objects.all (). Aggregate (Avg ("age"), Max ("age"), Min ("age"), Sum ("age"))
By default (average age in User):
Specify the key name (average age in User):
2.Q query: if you need to execute more complex queries (such as OR statements)
You can use the Q object. Q objects can use the & (and) and | (or) operators; use the ~ (not) operator to denote the inverse in front of the Q object
# query rs = User.objects.filter (Q (name=' Xiaoming') | Q (name=' Xiao Hong')) in the User table where name is Xiaoming or Xiaoxong (Q) # query Student table, rs = User.objects.filter (Q (name=' Xiaoming') & Q (age=18)) 3.F query: (query a whole column of data! )
Comparison of values for two fields
# the id of the college is less than the student's student number rs = Student.objects.filter (department_id__gt=F ('s_id)) # add 1-year-old rs = User.objects.all (). Update (age=F (' age') + 1) 4 to everyone in the User table. Grouping query
Generate a separate statistical value for each object in the called QuerySet
4.1 one-to-many relationship import Student,Coursefrom django.db.models import Count# takes out the fields that need to be grouped in the student table rs = Student.objects.values () # showing all the information of all the queried data in the form of a dictionary "" output example: