Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use django+mysql

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article will explain in detail how to use django+mysql. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Each model model in Django corresponds to a table in the database, and the fields in each model correspond to the columns of the database table. Conveniently, django can automatically generate these create table, alter table, drop table operations. Secondly, Django also provides us with a background management module (Django-Admin). The main function is to achieve the function of the client through background management, which can add, delete, modify and query data. You can also use this function to configure mysql in the secondary development Django.

In the previous installment, we learned about the settings.py configuration information, where DATABASES is used to manage database configuration, and the default is the sqlite3 database, so we need to modify it to a mysql database.

# Database

# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

# Database configuration 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', # password

'HOST':' 127.0.0.1, # HOST

'POST': 3306, # port

}

}

The corresponding instructions have been added to the field name code. ENGINE is the MYSQL database engine. Of course, this will not appear out of thin air, so we need to install it.

Install pymysql

Pip3 install pymysql

Configuration in the project

Make the following configuration in _ _ init__.py under the original project package

"

The configuration in setting defaults to sqlite3 database when it needs to be modified to MySql

And add the following configuration to _ _ init__.py in the sibling directory of setting.py

Otherwise, an error will be reported: Error loading MySQLdb module.

"

Import pymysql

Pymysql.install_as_MySQLdb ()

If the mysql configuration information is incorrect (username, password, host, etc.), the console will report the following exception

Pymysql.err.OperationalError: (1045, "Access denied for user 'ROOT'@'localhost' (using password: YES)")

Create Student (student information) and StudentUnion (community information) in the models.py file of the app file

Models.py: data module for database design

"

Create a student information table model

"

From django.db import models

"

This class is used to generate the database must inherit models.Model

"

Class Student (models.Model):

"

Create the fields of the following tables

"

# student number primary_key=True: this field is the primary key

StudentNum = models.CharField ('student ID', primary_key=True, max_length=15)

# maximum length of name string 20

Name = models.CharField ('name', max_length=20)

# Age integer null=False, indicating that the field cannot be empty

Age = models.IntegerField ('age', null=False)

# default True for gender Boolean type: male False: female

Sex = models.BooleanField ('gender', default=True)

# Mobile unique=True. This field is unique.

Mobile = models.CharField ('mobile phone', unique=True, max_length=15)

# creation time auto_now_add: it will only take effect when it is added

CreateTime = models.DateTimeField (auto_now_add=True)

# modification time auto_now: both additions and modifications will change the time

ModifyTime = models.DateTimeField (auto_now=True)

# specify the table name without specifying the default APP name-class name (app_demo_Student)

Class Meta:

Db_table = 'student'

"

Student association information table

"

Class studentUnion (models.Model):

# self-adding primary key. The default attribute cannot be set here, so elements will not be added but modified when the save is executed.

Id = models.IntegerField (primary_key=True)

# name of the community

UnionName = models.CharField ('club name', max_length=20)

# number of associations

UnionNum = models.IntegerField ('number of people', default=0)

# the person in charge of the community associates the primary key of Student, that is, the one-to-one relationship of studentNum student number. The on__delete attribute is required after django2.0. It will be described later.

UnionRoot = models.OneToOneField (Student, on_delete=None)

Class Meta:

Db_table = 'student_union'

"

OneToOneField: one-on-one

ForeignKey: one to many

ManyToManyField: many-to-many (no ondelete attribute)

"

Before using the models.py file to generate database tables, we need to create the database manually:

Mysql > create database django_mysql

Query OK, 1 row affected (0.01sec)

After creating the django_msql library, we execute the following command on the terminal, whose function is to generate a migration file from the models file

Python3 manage.py makemigrations

After the migration file is generated, execute

Python3 manage.py migrate

The contents of the migration file are applied to the database, tables are generated, or field properties are modified

If the output of the console is as follows, the execution is successful.

(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

Check out our django_mysql database, where student and student_union are tables generated by models files, and other tables are automatically generated by the project, so you can ignore them for the time being.

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)

Table structure

Desc view 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)

At this point, the function of Django to create database tables using models files is complete. Next, we will demonstrate how to add, delete, modify and check Django in a code way.

Increase data

In order to provide some test data, a few simple pieces of data are added in batches with for loops.

From app_demo.models import Student

Import random

"

Insert test data

"

Def insert (request):

# Random integers as student numbers

For i in range (0,5):

StudentNum = int (random.uniform (0,1) * 10000000000)

# get student objects from models files

Student = Student ()

# assign values to objects

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 insertion complete')

Configuration in urlpatterns in urls.py file

Url (r'^ insert/', views.insert)

Visit the http://localhost:8000/insert/ browser in the browser and display "data insertion complete"

Query the database and find that there are 5 days of data, that is, the insertion is successful.

Mysql > select * from student

+-+

| | studentNum | name | age | sex | mobile | createTime | modifyTime | |

+-+

| | 1352687635 | tom2 | 15 | 1 | 941807449 | 2018-11-08 09Fringe 585 | 40.226856 | 2018-11-08 09Fringe 40.227002 |

| | 5554311867 | tom0 | 15 | 0 | 1598619027 | 2018-11-08 09VOR 58VAND 40.203807 | 2018-11-08 09VOR 58RU 40.203960 |

| | 7302510986 | tom4 | 15 | 0 | 9602601619 | 2018-11-08 09-14 79 | 2018-11-08 09-14 79 | 2018-11-08 09 / 58 |

| | 847849420 | tom3 | 15 | 0 | 195276039 | 2018-11-08 09VOR 58VOR 40.238601 | 2018-11-0809PUBG 58ROR 40.238928 |

| | 9962892430 | tom1 | 15 | 0 | 3265013828 | 2018-11-08 09Fringe 585 | 40.215488 | 2018-11-08 09Fringe 40.216106 |

+-+

5 rows in set (0.00 sec)

Query data

"

Query

"

Def find (request):

# sql = 'select * from student'

# django can also execute native sql statements

# result = Student.objects.raw (sql)

# query the data of name = tom1

Result = Student.objects.filter (name='tom1')

"

Object for which result is

Data processing is needed.

"

Arr = []

For i in result:

Content = {'student number': i.studentNum, 'name': i.name, 'gender': i.sex}

Arr.append (content)

Print (arr)

Print (type (arr))

Return HttpResponse (arr)

Configure urls, and browsers access localhost:8000/find/

Modify data

"

Modify

"

Def modify (request, studentNum):

# get the student object through the student number

Student = Student.objects.get (studentNum=studentNum)

# set the name of student to jack

Student.name = 'jack'

Student.save ()

Return HttpResponse ('modified successfully')

The configuration in the setting file is as follows

Url (r'^ modify/ (? P\ d +)', views.modify)

Change the name of student number 847849420 to jack

Query the mysql database again and find that name has been updated to jack

Mysql > select * from student where studentNum='847849420'

+-+

| | studentNum | name | age | sex | mobile | createTime | modifyTime | |

+-+

| | 847849420 | jack | 15 | 0 | 195276039 | 2018-11-08 09VOR 58VAND 40.238601 | 2018-11-08 10VOR 22VOR 46.403147 |

+-+

1 row in set (0.00 sec)

Delete data

"

Delete

"

Def delete (request, studentNum):

Student = Student.objects.get (studentNum=studentNum)

Student.delete ()

Return HttpResponse ('deleted successfully')

The configuration of urlpatterns in settings.py is as follows

Url (r'^ delete/ (? P. +)', views.delete)

. + means to match multiple characters (excluding characters such as line feeds)

The browser requests the view

Query the database and find that the data has been deleted

Mysql > select * from student where studentNum='847849420'

Empty set (0.01sec on "how to use django+mysql" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report