Python path [Chapter 2]: Django database object relationship ing, pythondjango
Basic configurations of Django ORM
So far, when our program involves database-related operations, we generally do this:
- Create a database and design the table structure and fields
- Use MySQLdb to connect to the database and write data access layer code
- The business logic layer calls the data access layer to perform database operations
Django adopts a new method, namely Object Relational Mapping (ORM). django follows the Code Frist principle, that is: automatically generate database tables based on classes defined in the Code
1. Modify the project Database Configuration(Settings. py file in the main directory of the Program)
The default Connection database is the local file sqlite3:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}
Replace with the specified mysql database:
DATABASES = {'default': {'Engine ': 'django. db. backends. mysql ', 'name': 'zyweb', # Database NAME 'user': 'root', # account 'Password': 'zyw @ 123', # PASSWORD 'host ': '2017. 168.28.129 ', # mysql database IP address 'Port': '000000', # peer PORT }}
2. Create a table structure file for the database.(Corresponding to the models. py file in the app directory)
Generate a simple database table:
From django. db import models # Create your models here. class UserInfo (models. model): # The Name Of The created table is cmdb_userinfo # The database creates the id column auto-incrementing primary key by default # username column string type character length username = models. charField (max_length = 32) passwd = models. charField (max_length = 64)
Add the corresponding app name to the settings. py file Configuration:
INSTALLED_APPS = ['django. contrib. admin', 'django. contrib. auth ', 'django. contrib. contenttypes ', 'django. contrib. sessions ', 'django. contrib. messages ', 'django. contrib. staticfiles ', 'cmdb', # The system will load the model under the cmdb. py file]
3. Generate database tables
Run the following command:
Python manage. py makemigrationspython manage. py migrate # generate a data table
View database table details:
mysql> desc cmdb_userinfo;+----------+-------------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+----------+-------------+------+-----+---------+----------------+| id | int(11) | NO | PRI | NULL | auto_increment || username | varchar(32) | NO | | NULL | || passwd | varchar(64) | NO | | NULL | |+----------+-------------+------+-----+---------+----------------+3 rows in set (0.01 sec)
Note: Django uses the MysqlDB module by default to connect to the database, but this module is not available in python3.x. All modules that need to be connected to the database should be changed to pymsyql and the init. py file under the project directory should be modified.
import pymysqlpymysql.install_as_MySQLdb()
4. database fields and field parameters
1. models. autoField auto-increment column = int (11) if not, a column named id is generated by default. If you want to display a Custom Auto-increment column, you must set the primary key primary_key = True for the column. 2. models. the CharField string field must have the max_length parameter 3 and models. booleanField boolean type = tinyint (1) cannot be Blank, Blank = True4, models. comaSeparatedIntegerField is a comma-separated number = varchar inherits CharField, so max_lenght parameters 5 and models are required. dateField date: for the parameter auto_now = True, this time is updated for each update. auto_now_add is only created and added for the first time, and subsequent updates are not changed. 6. models. dateTimeField datetime is the same as DateField parameter 7 and models. decimal decimal Decimal type = decimal must specify the integer max_digits, decimal_places8, and models. emailField string type (Regular Expression mailbox) = varchar Regular Expression 9, models. floatField floating point type = double10, models. integerField integer 11, models. bigIntegerField long integer integer_field_ranges = {'smallintegerfield ': (-32768,327 67), 'integerfield': (-2147483648,214 7483647), 'bigintegerfield ': (-92233720368 54775808,922 3372042554775807), 'positivesmallintegerfield ': (0, 32767), 'positiveintegerfield': (0, 2147483647),} 12 ,! Models. IPAddressField string type (ip4 Regular Expression) no longer uses 13, models. the parameter protocol of the GenericIPAddressField string type (ip4 and ip6 are optional) can be both, ipv4, or ipv6 verification. Errors 14 and models are reported according to the settings. nullBooleanField allows null Boolean types 15, models. positiveIntegerFiel is Integer16, models. positiveSmallIntegerField is smallInteger17, models. slugField minus signs, underscores, letters, numbers 18, models. smallIntegerField: tinyint, smallint, int, bigint19, models. textField string = longtext20, models. timeField time HH: MM [: ss [. uuuuuu] 21. models. URLField string, address regular expression 22, models. binaryField binary 23, models. imageField image 24, models. filePathField FileAll fields...
Null-> whether db can be empty default-> default value primary_key-> Primary Key db_column-> column name db_index-> index unique-> unique index unique_for_date-> unique_for_monthunique_for_yearauto_now->, automatic Generation Time auto_now_add-> Update, automatically updated to the current time choices-> django admin display drop-down box, avoid table connection query blank-> django admin whether it can be blank verbose_name-> django admin display field Chinese editable-> django admin whether it can be edited error_messages-> error message owed help_text-> django admin prompts validators-> djangoform, custom error message (owed)
All field parameters...
Django database operations
1. Add data
Method 1 (most commonly used ):
from cmdb import modelsdef ormadd(request): models.UserInfo.objects.create(username="James",passwd="8888") return HttpResponse("ormadd")
Another method is as follows:
from cmdb import modelsdef ormadd(request): dicts = {'username':"James",'passwd':"8888"} models.UserInfo.objects.create(**dicts) return HttpResponse("ormadd")
Method 2:
from cmdb import modelsdef ormadd(request): obj = models.UserInfo(username='root',passwd='123') obj.save() return HttpResponse("ormadd")
2. query data
Query all:
From cmdb import modelsdef ormselect (request): result = models. userInfo. objects. all () print (result) # each element in the QuerySet type list is an obj object # <QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: userInfo object>]> for row in result: print (row. id, row. username, row. passwd) #1 James 8888 #2 root 123 #3 James 8888 return HttpResponse ("ormselect ")
Search for a specified field:
From cmdb import modelsdef ormselect (request): result = models. userInfo. objects. filter (username = 'root') # It Can Be Used in filter () to separately represent and if result: for row in result: print (row. id, row. username, row. passwd) #2 root 123 return HttpResponse ("ormselect ")
Obtain the first data query and the number of matching statistics:
From cmdb import modelsdef ormselect (request): obj = models. userInfo. objects. filter (username = 'root '). filter () # obtain the matching first field c = models. userInfo. objects. filter (username = 'root '). count () # obtain the number of matched fields return HttpResponse ("ormselect ")
3. delete data
Delete a specified field:
from cmdb import modelsdef ormdel(request): models.UserInfo.objects.filter(id=3).delete() return HttpResponse("ormdel")
4. Update Data
Update a specified field:
from cmdb import modelsdef ormupdate(request): models.UserInfo.objects.filter(id=2).update(passwd='99999') return HttpResponse("ormupdate")
5. Single Table foreign key Association
Database table structure:
From django. db import models # Create your models here. class UserInfo (models. model): # The Name Of The created table is cmdb_userinfo username = models. charField (max_length = 32) passwd = models. charField (max_length = 64) # The field name generated by the associated foreign key is user_group_id user_group = models. foreignKey ("UserGroup", to_field = 'uid', default = 1) # The uid field associated with the usergroup table is 1 class UserGroup (models. model): # The Name Of The created table is cmdb_usergroup uid = models. autoField (primary_key = True) # primary key auto-increment caption = models. charField (max_length = 32, unique = True) # unique index ctime = models. dateField (auto_now_add = True, null = True) # creation time uptime = models. dateField (auto_now = True, null = True) # Update indicates the automatic update time.
Foreign key join table operation:
From cmdb import modelsdef ormadd (request): models. userInfo. objects. create (username = "James", passwd = "8888") return HttpResponse ("ormadd") def ormgroup (request): models. userGroup. objects. create (caption = "CEO") return HttpResponse ("ormgroup") def userinfo (request): obj = models. userInfo. objects. all (). first () # user_group_id specifies the ID print (obj. id, obj. username, obj. user_group_id) #1 James 1 # user_group specifies the obj object print (obj. user_group.uid, obj. user_group.caption) #1 CEO return HttpResponse ("userinfo ")