Django basic model (database)

Live well, love lots, and laugh often
Be kind to life, love everything, often laugh loudly

This article is mainly used to record the relevant parts of the Django model, the model can be simply understood as data operations, that is, to obtain data from the database, to store data in the database. Django uses sqlite3 by default and supports databases such as mysql and postgreSQL.

settingConfiguring database connection

The default is sqlite3

1
2
3
4
5
6
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

Modified to mysql configuration:

1
2
3
4
5
6
7
8
9
10
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}

NAME: The specified database name, if it is sqlite, you need to fill in the absolute location of the database file.
USER: User name for database login, mysql is generally root
PASSWORD: The password for logging in to the database must be the password corresponding to the USER user.
HOST: Since the general database is C/S structure, we have to specify the location of the database server. Our general database server and client are all on one host, so the default is 127.0.0.1.
PORT: database server port, mysql defaults to 3306
HOST and PORT can be left blank, using the default configuration

Create a table

The following way is suitable for mysql, sqlite3 and other databases, in addition mysql needs to install mysql-python (pip install mysql-python)

Creating a table field in models.py

1
2
3
4
5
from django.db import models
class auth(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=100)

Description: Create an auth table with the fields username, password, followed by the field data type and the maximum length.

Execute command to create a table

1
python manage.py makemigrations

Synchronizing database tables

1
python manage.py migrate

Using a data table (QuerySet)

Testing in the Django shell

Run: python manage.py shell

1
2
3
4
5
6
7
>>>from webapp.models import auth
>>>p = auth(username="nmask", password="nmask")
>>>p.save()
>>>L=auth.objects.all()
>>>for i in L:
>>> print i.username
nmask

Description: The method used in View.py is similar to that in the shell.

How to insert content into the data table

1
2
3
4
5
6
7
8
9
10
11
12
The first:
auth.objects.create(username="nmask",password="nmask")
Second:
p = auth(username="nmask",password="nmask")
p.save()
The third type:
p = auth(username="nmask")
p.password = "nmask"
p.save()
Fourth:
auth.objects.get_or_create(username="nmask",password="nmask")
Description: This method will determine whether it exists, return a tuple, the first one is auth object, the second is True (there is no existing) or False (present).

How to query content from a data table

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
auth.objects.all()
Auth.objects.all()[:2] is equivalent to limit and only gets 2 results
Auth.objects.get(name="nmask") get is used to get an object
Auth.objects.filter(name="nmask") A person whose name is strictly equal to "abc"
Auth.objects.filter(name__exact="nmask") A person whose name is strictly equal to "abc"
Auth.objects.filter(name__iexact="nmask") name is abc but not case sensitive
Auth.objects.filter(name__contains="nmask") person with "abc" in its name
Auth.objects.filter(name__icontains="nmask") contains "abc" in the name, and abc is not case sensitive
Auth.objects.filter(name__regex="^nmask") regular expression query
Auth.objects.filter(name__iregex="^nmask") Regular expressions are not case sensitive
Auth.objects.exclude(name__contains="nmask") Excludes auth objects containing nmask
Auth.objects.filter(name__contains="nmask").filter(password="nmask") Find out that the account password is nmask
Auth.objects.filter(name__contains="nmask").exclude(passowrd="nmask") find out that the name contains nmask, but exclude password from nmask
Auth.objects.all().order_by('name') Sort results
Auth.objects.all().order_by('-name') implements reverse order
res = auth.objects.all()
Res = res.distinct()
Auth.objects.get(name="nmask").only("password") returns only the password field

Update data table content

Single update:

1
2
3
response = auth.objects.get(username="nmask")
response.password="123"
response.save()

Batch update:

1
auth.objects.filter(name__contains="nmask").update(name='nMask')

Delete data table content

Single delete:

1
2
3
response = auth.objects.get(username="nmask")
response.password="123"
response.delete()

batch deletion:

1
auth.objects.filter(name__contains="nmask").delete()

Using the connection function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.db import connection
def search_db(sql,value):
'''Operation database'''
result_list=[]
cursor = connection.cursor()
try:
cursor.execute(sql,value)
result_list=cursor.fetchall()
cursor.close()
except Exception,e:
print is
return result_list

本文标题:Django basic model (database)

文章作者:nmask

发布时间:2017年09月14日 - 20:09

最后更新:2019年07月11日 - 15:07

原始链接:https://thief.one/2017/09/14/2/en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

nmask wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!

热门文章推荐: