Each model in Django corresponds to a table in the database, and each field in the model corresponds to a column in the database table. Conveniently, Django automatically generates these create TABLE, ALTER TABLE, and drop table operations. Second, Django also provides a background management module for us (Django-admin), the main function is to achieve the client function through the background management, you can add, delete, change and check data. It can also be used for secondary development
Mysql configuration in Django
In the previous installment, we looked at settings.py configuration information, where DATABASES is used to manage database configuration. The default is SQlite3 database, so we need to change it to mysql database.
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
The default database is SQLite
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#}
#}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql'.# database engine
'NAME': 'django_mysql'.# database name
'USER': 'root'.# account
'PASSWORD': 'root'.# your password
'HOST': '127.0.0.1'.# HOST
'POST': 3306, # port}}Copy the code
ENGINE is the MYSQL database ENGINE. This does not appear in a void, we need to install it
Install pymysql
pip3 install pymysql
Copy the code
Project Configuration
Do the following in __init__.py under the original project package
""Setting: Error loading MySQLdb module. Setting: Error loading MySQLdb module.""
import pymysql
pymysql.install_as_MySQLdb()
Copy the code
If the mysql configuration information is incorrect (such as the user name, password, or host), the console reports the following exception
pymysql.err.OperationalError: (1045, "Access denied for user 'ROOT'@'localhost' (using password: YES)")
Copy the code
Create Student and StudentUnion in the models.py file of your app file.
Models.py: Data module for database design
"""Create student information sheet model"""
from django.db import models
"""This class is used to generate the database and must inherit models.model"""
class Student(models.Model):
"""Create fields for the following tables"""
# Primary key=True: This field is the primary key
studentNum = models.CharField('student id', primary_key=True, max_length=15)
The value contains a maximum of 20 characters
name = models.CharField('name', max_length=20)
# Age integer null=False, indicating that the field cannot be empty
age = models.IntegerField('age', null=False)
# Gender Boolean defaults to True: male False: female
sex = models.BooleanField('gender', default=True)
# phone unique=True
mobile = models.CharField('mobile phone', unique=True, max_length=15)
Auto_now_add: This takes effect only when it is added
createTime = models.DateTimeField(auto_now_add=True)
Auto_now: Both additions and modifications change the time
modifyTime = models.DateTimeField(auto_now=True)
Class name (app_demo_Student)
class Meta:
db_table = 'student'
"""Student Club Information Sheet"""
class studentUnion(models.Model):
# add primary key (' default ')
id = models.IntegerField(primary_key=True)
# Club Name
unionName = models.CharField('Name of Society', max_length=20)
# Number of clubs
unionNum = models.IntegerField('number', default=0)
StudentNum is the primary key of Student. On__delete is mandatory after Django2.0
unionRoot = models.OneToOneField(Student, on_delete=None)
class Meta:
db_table = 'student_union'
"""OneToOneField: one-to-one ForeignKey: one-to-many ManyToManyField: many-to-many (no ondelete attribute)"""
Copy the code
Before using the models.py file to generate the database table, we need to create the database manually:
mysql> create database django_mysql; Query OK, 1 row affected (0.01sec)Copy the code
After creating the django_mSQL library, we execute the following command on the terminal to generate a migration file from the Models file
python3 manage.py makemigrations
Copy the code
python3 manage.py migrate
Copy the code
The contents of the migrated file are applied to the database, tables are generated, or field properties are modified
If the console output is as follows, the command is executed successfully
(django_venv) xxxxxdeAir:djangoDemo xxxxx$ python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, app_demo, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying app_demo.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying sessions.0001_initial... OK
Copy the code
Take a look at our django_mysql database, where student and student_union are the tables generated with the models file, and the other tables are automatically generated by the project and can be left alone for now
mysql> use django_mysql
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_django_mysql |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
| student |
| student_union |
+----------------------------+
12 rows in set (0.00 sec)
Copy the code
Table structure
Desc Displays the table structure
mysql> desc student;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| studentNum | varchar(15) | NO | PRI | NULL | |
| name | varchar(20) | NO | | NULL | |
| age | int(11) | NO | | NULL | |
| sex | tinyint(1) | NO | | NULL | |
| mobile | varchar(15) | NO | UNI | NULL | |
| createTime | datetime(6) | NO | | NULL | |
| modifyTime | datetime(6) | NO | | NULL | |
+------------+-------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
mysql> desc student_union;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| unionName | varchar(20) | NO | | NULL | |
| unionNum | int(11) | NO | | NULL | |
| unionRoot_id | varchar(15) | NO | UNI | NULL | |
+--------------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
Copy the code
This completes Django’s ability to create database tables from the Models file. Next, we’ll show you how to add, delete, change, and check Django in code
Increase the data
To provide some test data, we add a few simple pieces of data in batches using the for loop.
from app_demo.models import Student
import random
"""Insert test data"""
def insert(request):
# Random integer as student number
for i in range(0, 5):
studentNum = int(random.uniform(0, 1) * 10000000000)
Get the student object from the Models file
student = Student()
# Assign to the object
student.studentNum = studentNum
student.name = 'tom' + str(i)
student.age = 15
student.sex = random.choice([True, False])
student.mobile = int(random.uniform(0, 1) * 10000000000)
# insert data
student.save()
return HttpResponse('Data inserted complete')
Copy the code
Configured in urlpatterns in urls.py
url(r'^insert/', views.insert)
Copy the code
The browser to http://localhost:8000/insert/ in the browser display ‘data into finished’
Query the database and find that there is 5 days of data, that is, the insert is successful
mysql> select * from student; +------------+------+-----+-----+------------+----------------------------+----------------------------+ | studentNum | name | age | sex | mobile | createTime | modifyTime | + -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- - + -- -- -- -- -- + + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + | | 1352687635 Tom2 15 | 1 | | 941807449 | 2018-11-08 09:58:40. 226856 | 2018-11-08 09:58:40. 227002 | | 5554311867 | tom0 15 | | | 0 1598619027 | 2018-11-08 09:58:40. 203807 | 2018-11-08 09:58:40. 203960 | | 7302510986 | tom4 | | 9602601619 | | 0 15 The 2018-11-08 09:58:40. 251479 | 2018-11-08 09:58:40. 251682 | | 847849420 | tom3 | | 195276039 | | 0 15 2018-11-08 09:58:40. 238601 | 2018-11-08 09:58:40. 238928 | | 9962892430 | tom1 | | 0 | 3265013828 | 2018-11-08 09:58:40. 15 215488 | The 2018-11-08 09:58:40. 216106 | +------------+------+-----+-----+------------+----------------------------+----------------------------+ 5 rowsin set (0.00 sec)
Copy the code
Query data
"""Query"""
def find(request):
#sql = 'select * from student'
Django can also execute native SQL statements
#result = Student.objects.raw(sql)
Select * from tom1 where name = tom1
result = Student.objects.filter(name='tom1')
"""The result for < class 'django. Db. Models. Query. QuerySet' > object data processing is required"""
arr = []
for i in result:
content = {'student id': i.studentNum, 'name': i.name, 'gender': i.sex}
arr.append(content)
print(arr)
print(type(arr))
return HttpResponse(arr)
Copy the code
Configure urls with the browser accessing localhost:8000/find/
Modify the data
"""Change"""
def modify(request, studentNum):
Get student object by student id
student = Student.objects.get(studentNum=studentNum)
# set student's name to jack
student.name = 'jack'
student.save()
return HttpResponse('Modified successfully.')
Copy the code
The configuration in the setting file is as follows
url(r'^modify/(? P
\d+)'
, views.modify),
Copy the code
Example Change the name of student ID 847849420 to Jack
mysql> select * from student where studentNum='847849420'; +------------+------+-----+-----+-----------+----------------------------+----------------------------+ | studentNum | name | age | sex | mobile | createTime | modifyTime | + -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- - + -- -- -- -- -- + + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + | | 847849420 Jack | | 0 | 195276039 | 2018-11-08 09:58:40. 15 238601 | 2018-11-08 10:22:46. 403147 | +------------+------+-----+-----+-----------+----------------------------+----------------------------+ 1 rowin set (0.00 sec)
Copy the code
Delete the data
"""Delete"""
def delete(request, studentNum):
student = Student.objects.get(studentNum=studentNum)
student.delete(
return HttpResponse('Delete successful.')
Copy the code
The configuration of urlpatterns in settings.py is as follows
url(r'^delete/(? P
.+)'
, views.delete)
Copy the code
.+ matches multiple characters (excluding newlines)
The browser requests the view
mysql> select * from student where studentNum='847849420';
Empty set (0.01 sec)
Copy the code
Pay attention to the public account “Programmers grow together” (ID: FinishBug). We have prepared rich gifts for new partners, including but not limited to: Python, Java, Linux, big data, artificial intelligence, front-end and other 21 technical directions. You can get the “gift package” by responding to the background.