Django database ORM operations-create, add, delete, change and query single tables
In Django, managing the database is similar to sqlarchemy, which is also implemented through the orm framework. All the establishment of the database is realized through classes in model.py.
First, take a look at how to create a single table:
a. First define a class, inherit models.Model, and then define parameters according to the requirements. The types and variables of these parameters will be further described later.
Models.py
From django.db import modelsclass UserInfo (models.Model): username = models.CharField (max_length=32) password = models.CharField (max_length=64)
b. Register for app
Settings.py
INSTALLED_APPS = ['django.contrib.admin',' django.contrib.auth', 'django.contrib.contenttypes',' django.contrib.sessions', 'django.contrib.messages',' django.contrib.staticfiles', 'app01',]
c. Carry out the order. The first command generates an initialization file, and the second command generates the corresponding table.
Python manage.py makemigrationspython manage.py migrate
In this way, an app01_UserInfo table is successfully generated in the sqlite database that comes with PyCharm. This table defaults to having a self-increasing id as the primary key, and the other two fields are created by class.
d. If you want to use mysql, because Django uses the MySqldb module by default, which does not exist in version 3.0, an error will be reported directly. We need to change the module to pymysql as follows:
Add the following code to the _ _ init__ file under the project folder with the same name:
Import pymysql
Pymysql.install_as_MySQLdb ()
two。 Query for addition, deletion and modification of a single table
Query
Get all the results, the result is a QuerySet-like list of objects, each element itself is an object, including attributes such as id,name,password.
Obj = models.UserInfo.objects.all ()
You can filter through filter, which is equivalent to the where statement of sql, because the result is also QuerySet, so you need to use first () to get the first value again.
Obj = models.UserInfo.objects.filter (id=nid). First ()
Increase
Models.UserInfo.objects.create (username=u,password=p,user_group_id=3)
Delete, which can be deleted on the basis of filter
Models.UserInfo.objects.filter (id=nid) .delete ()
There are two common ways to modify
The first way
Models.UserInfo.objects.filter (id=nid) .update (username=u,password=p)
The second way
Obj=models.UserInfo.objects.filter (id=nid) obj.username=uobj.save ()