Django web frame of the Python ORM database operations Analysis

1. The construction of the table
under the first reference model may be set in various field types
to create a table in the model
from django.db import models

Create your models here.

the Person class (models.Model):
# define a user name field, can not be repeated
username = models.CharField (= 10 MAX_LENGTH, UNIQUE = True)
password = (MAX_LENGTH = 10) models.CharField
# Default settings. 1
Age = Models .IntegerField ()
#False on behalf of the representative female male True 1 M to 0
Sex = models.BooleanField (default = False)
# by specifying the attributes to set the column names generated, but the use of the class or p_des
p_des = models.CharField (MAX_LENGTH = 100, the db_column = 'des')
CREATE_DATE = models.DateTimeField (auto_now = True)
class Meta -:
# designated generation table, not specify a default format is generated APP + class name
named db_table, = 'User'
Python Manage. makemigrations Py
Python manage.py the migrate
random codes generated by such data, there is a small pit, you may encounter =. =
DEF the addUser (Request):
for I in Range (. 5):
Person = the Person ()
random.randrange = NUM (100)
person.username = 'Sola D%'% NUM
person.password = '% Pass D' NUM%
person.age NUM =
person.sex NUM = 2%
person.save ()
return the HttpResponse ( "Success")
2. conditions queries
available through the filter and to exclude the chain query.
getUser DEF (Request):
# can be queried (meet) through the filter, you can continue to chain multiple conditions.
= Person.objects.filter #users (username the contains = "5"). filter (username the contains = 3)
# can also be used to query by exclude (not satisfied)
the Users = Person.objects.exclude (username the contains = "5 ") .filter (username the contains =". 9 ")
for Users in User:
Print (user.username)
Print (user.create_date)
return the HttpResponse (" Success ")
. 3. 
addUserTwo DEF (Request):
User = Person.objects.create (username = '~ RUI', password = 'RUI!', Age = 18 is)
user.save ()
return the HttpResponse ( "Success")
4. Sort
def getUser ( Request):
# order_by added directly to sorting based on the field, the default is the positive sequence, plus or minus sign in front of flashback
Users = Person.objects.filter (Age in = [ '73 is', '34 is', '84']) order_by. ( "-username")
for Users in User:
Print (user.username)
Print (user.create_date)
return the HttpResponse ( "Success")
5. the data is converted into the dictionary (converted into the Map)
DEF the getUser (Request):
#values the results can be directly converted into a dictionary, the dictionary can be transferred directly through the tool into JSON
Users = Person.objects.filter (Age
in = [ '63 is', '50', '36', '. 11']). values ()
for user in users:
print(user.username)
print(user.create_date)
Print (user.sex)
return the HttpResponse ( "Success")
6. The second query (Query results again query)
DEF the getUser (Request):
Users = Person.objects.filter (age__in = [ '63 is',' 50 ',' 36 ',' 11 '])
# may again query
Users = users.filter (Age = '50')
for Users in User:
Print (user.username)
Print (user.create_date)
Print (user.sex)
return the HttpResponse ( "Success")
7. the query slice
DEF the getUser (Request):
# query slices, beginning from the fourth, the fifth, can not have negative
Users = Person.objects.all () [. 3:. 5]
for User the Users in:
Print (user.username)
Print (user.create_date)
Print (user.sex)
return HttpResponse ( "Success")
8. ignore case the query
before the query can join i
9. Change time zone setting
The default set of time zone Django custom general database does not match, the query result is not accurate, it is required to turn off the setting
# default is True, False changed to
USE_TZ = False
10. The aggregation function
def getUser (request) :
# aggregation function, Avg. The average number Count, Max Max, Min Min, sum summation; fill parameter field
avgNum Person.objects.aggregate = (Avg. ( "Age"))
Print (avgNum)
return the HttpResponse ( "Success" )
11. a field of a comparison
DEF the getUser (Request):
# a field in a data comparison, can be equal to the size, and the like comprising
#users = Person.objects.filter (Age = F. ( "ID"))
# can can write, age greater than +. 1 ID
Users = Person.objects.filter (Age gt = F. ( "ID") +. 1)
function () {// point calculator http://www.fx61.com/dotpoint .html
Print (users.values ())
return the HttpResponse ( "Success")
12. the logical operator query written
def getUser (request):
= Person.objects.filter Users (Q (Age
gt = 90) & Q (age__lt = 100))
Print (users.values ())
return the HttpResponse ( "Success")
13. Some default query package
because the query is Django automatically generated by the query objectsManager in model, we can create a class that inherits from Manager, and rewrite his query methods, give the Model class objects to objects given parameters, and then query by calling the objects parameter, you will want to filter the default filter conditions.
Model
# song class management
class SongManager (models.Manager):
DEF get_queryset (Self):
. Super return (SongManager, Self) .get_queryset () filter (is_deleter = 1)
# inherit song management class
class Song (models.Model):
name = models.CharField (max_length = 50)

length = models.CharField(max_length=10)
is_deleter = models.IntegerField(max_length=1,default=0)
singer = models.CharField(max_length=30) 
objects = SongManager()

views
def getSong(request):
songs = Song.objects.all()
for song in songs:
print(song.name)
return HttpResponse("success")
原文链接:blog.csdn.net/jiulanhao/article/details/103027355

Guess you like

Origin blog.51cto.com/14511863/2450372