Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Django ORM – Single Table Example

Django ORM - Single Table Example

Before reading this chapter, you need to have first read Django Models for basic configuration and to understand solutions to common problems.

Next, we recreate a project app01 (if it was created before, ignore the following steps):



django-admin.py startproject app01

Next, find the INSTALLED_APPS item in settings.py, as follows:



INSTALLED_APPS = (

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'app01',               # 添加此项

)

Next, tell Django to use the pymysql module to connect to the mysql database:

Example

In the directory at the same level as settings.py, initimport the module and configure it in the .py

import

pymysql

pymysql.

install_as_MySQLdb

(

)

Create the model

Add the following classes to models.py in the project:

app01/models.py

class Book

(

models.Model

)

:

   

id

= models.AutoField

(

primary_key

=True

)

id is created automatically and can also be written manually

    title = models.CharField

(

max_length

=

32

)

Book title

    price = models.DecimalField

(

max_digits

=

5

,

decimal_places

=

2

)

Book price

    publish = models.CharField

(

max_length

=

32

)

Publisher name

    pub_date = models.DateField

(

)

Publication time

Then run the following command in the command line:



$ python3 manage.py migrate   # 创建表结构



$ python3 manage.py makemigrations app01  # 让 Django 知道我们在我们的模型有一些变更

$ python3 manage.py migrate app01   # 创建表结构

Common error messages

If the following error message appears when running the above command:

The reason is that MySQLclient currently only supports up to Python 3.4, so if you are using a higher version of Python, you need to modify the following:

Use the file path in the error message to find the base.py file in the path ...site-packages\Django-2.0-py3.6.egg\django\db\backends\mysql, and comment out these two lines of code (the code is at the beginning of the file):

if version < (1, 3, 13):

    raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)

Generally, clicking on the code file path information in the error automatically jumps to the line number in the error file, where we then comment out the line.

At this point, the database runoob will create a table named app01_book.

Next, we add views.py and models.py files in the app01 project; the app01 project directory structure:



app01

|-- app01

|   |-- __init__.py

|   |-- __pycache__

|   |-- asgi.py

|   |-- migrations

|   |-- models.py

|   |-- settings.py

|   |-- urls.py

|   |-- views.py

|   `-- wsgi.py

Add data to the database

Rule configuration:

app01/urls.py: file code:

from

django

.

contrib

import

admin

from

django

.

urls

import

path

from

.

import

views

urlpatterns

=

[

path

(

'

add_book/

'

,

views

.

add_book

)

,

]

**Method 1:** Instantiate an object of the model class

You need to import the models.py file from the app directory:

from app 目录 import models

And after instantiating the object, you need to execute object.save() to successfully add it to the database.

app01/views.py: file code:

from

django

.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

book

=

models

.

Book

(

title

=

"

Runoob Tutorial

"

,

price

=

300

,

publish

=

"

Cainiao Press

"

,

pub_date

=

"

2008-8-8

"

)

book

.

save

(

)

return

HttpResponse

(

"

Data added successfully!

"

)

**Method 2:** Implemented through the create method provided by ORM's objects (recommended)

app01/views.py: file code:

from

django

.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

books

=

models

.

Book

.

objects

.

create

(

title

=

"

Rulai Shenzhang

"

,

price

=

200

,

publish

=

"

Kung Fu Press

"

,

pub_date

=

"

2010-10-10

"

)

print

(

books

,

type

(

books

)

)

Book object (18)

return

HttpResponse

(

"

Data added successfully!

"

)

Find

Use all() method to query all content.

The return is QuerySet type data, similar to a list, containing model class objects one by one; you can use index subscripts to retrieve model class objects.

app01/views.py: file code:

from

django

.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

books

=

models

.

Book

.

objects

.

all

(

)

print

(

books

,

type

(

books

)

)

The QuerySet type is similar to a list; when accessing the URL, the data is displayed in the command-line window.

return

HttpResponse

(

"

Query successful!

"

)

filter() The method is used to query data that meets the conditions.

The return is QuerySet type data, similar to a list, containing model class objects that meet the conditions; you can use index subscripts to retrieve model class objects.

pk=3 means the primary key primary key=3, equivalent to id=3.

Because id has a special meaning in pycharm, being the built-in function id() that views memory addresses, pk is used instead.

app01/views.py: file code:

from

django

.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

books

=

models

.

Book

.

objects

.

filter

(

pk

=

5

)

print

(

books

)

print

(

"

//////////////////////////////////////

"

)

books

=

models

.

Book

.

objects

.

filter

(

publish

=

'

Cainiao Press

'

,

price

=

300

)

print

(

books

,

type

(

books

)

)

The QuerySet type is similar to a list.

return

HttpResponse

(

"

Query successful!

"

)

**exclude() ** method is used to query data that does not meet the conditions.

The return is QuerySet type data, similar to a list, containing model class objects that do not meet the conditions; you can use index subscripts to retrieve model class objects.

app01/views.py: file code:

from

django

.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

books

=

models

.

Book

.

objects

.

exclude

(

pk

=

5

)

print

(

books

)

print

(

"

//////////////////////////////////////

"

)

books

=

models

.

Book

.

objects

.

exclude

(

publish

=

'

Cainiao Press

'

,

price

=

300

)

print

(

books

,

type

(

books

)

)

The QuerySet type is similar to a list.

return

HttpResponse

(

"

Query successful!

"

)

get() The method is used to query data that meets the conditions and returns a model class object; the matching object can only be one, and if more than one or no object matches the filter conditions, an error will be raised.

app01/views.py: file code:

from

django

.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

books

=

models

.

Book

.

objects

.

get

(

pk

=

5

)

books

=

models

.

Book

.

objects

.

get

(

pk

=

18

)

Error: no object meets the conditions

books

=

models

.

Book

.

objects

.

get

(

price

=

200

)

Error: more than one object meets the conditions

print

(

books

,

type

(

books

)

)

model class object

return

HttpResponse

(

"

Query successful!

"

)

order_by() The method is used to sort the query results.

The return is QuerySet type data, similar to a list, containing sorted model class objects; you can use index subscripts to retrieve model class objects.

Note:

app01/views.py: file code:

from

django

.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

books

=

models

.

Book

.

objects

.

order_by

(

"

price

"

)

Query all, sorted by price in ascending order

books

=

models

.

Book

.

objects

.

order_by

(

"

-price

"

)

Query all, sorted by price in descending order

return

HttpResponse

(

"

Query successful!

"

)

reverse() The method is used to reverse the query results.

The return is QuerySet type data, similar to a list, containing reversed model class objects; you can use index subscripts to retrieve model class objects.

app01/views.py: file code:

from

django

.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

Sorted by price ascending: descending then reversed

books

=

models

.

Book

.

objects

.

order_by

(

"

-price

"

)

.

reverse

(

)

return

HttpResponse

(

"

Query successful!

"

)

**count() ** method is used to query the quantity of data; the returned data is an integer.

app01/views.py: file code:

from

django

.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

books

=

models

.

Book

.

objects

.

count

(

)

Query the quantity of all data

books

=

models

.

Book

.

objects

.

filter

(

price

=

200

)

.

count

(

)

Query the quantity of data that meets the conditions

return

HttpResponse

(

"

Query successful!

"

)

first() The method returns the first piece of data; the returned data is a model class object; you can also use the index subscript [0].

app01/views.py: file code:

from

django

.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

books

=

models

.

Book

.

objects

.

first

(

)

Return the first piece of all data

return

HttpResponse

(

"

Query successful!

"

)

The last() method returns the last piece of data; the returned data is a model class object; you cannot use the index subscript [-1], because ORM has no reverse indexing.

app01/views.py: file code:

from

django

.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

books

=

models

.

Book

.

objects

.

last

(

)

Return the last piece of all data

return

HttpResponse

(

"

Query successful!

"

)

exists() The method is used to determine whether there is data in the query result QuerySet list.

The returned data type is boolean: true if present, false if not.

**Note:** The data type to be judged can only be QuerySet type data, not an integer or a model class object.

Example

from

django.

shortcuts

import

render

,

HttpResponse

from

app01

import

models

def

add_book

(

request

)

:

    books

=

models.

Book

.

objects

.

exists

(

)

   

Error: the judged data type can only be QuerySet type data, not an integer

    books

=

models.

Book

.

objects

.

count

(

)

.

exists

(

)

   

Error: the judged data type can only be QuerySet type data, not a model class object

    books

=

models.

Book

.

objects

.

first

(

)

.

exists

(

)

 

   

return

HttpResponse

(

"

Query successful!

"

)

values() The method is used to query data of some fields.

The return is QuerySet type data, similar to a list; inside are not model class objects but an iterable sequence of dictionaries, where the keys in each dictionary are fields and the values are data.

Note:

Example

from django.shortcuts import render,HttpResponse
from app01 import models
def add_book(request):
    # Query all data for the id field and price field
    books = models.Book.objects.values("pk","price")
    print(books[0]["price"],type(books)) # What is obtained is the data of the price field of the first record
    return HttpResponse("

Query successful!

"
)

values_list() The method is used to query data of some fields.

The return is QuerySet type data, similar to a list; inside are not model class objects but tuples one by one, each containing the data corresponding to the queried fields.

Note:

Example


from django.shortcuts import render,HttpResponse
from app01 import models
def add_book(request):
    # Query all data for the price field and publish field
    books = models.Book.objects.values_list("price","publish")
    print(books)
    print(books[0][0],type(books)) # What is obtained is the data of the price field of the first record
    return HttpResponse("

Query successful!

"
)

distinct() The method is used to deduplicate data.

The return is QuerySet type data.

Note:

Example

from django.shortcuts import render,HttpResponse
from app01 import models
def add_book(request):
    # Query how many publishers there are in total
    books = models.Book.objects.values_list("publish").distinct() # Deduplicating model class objects is meaningless, because every object is a distinct entity.
    books = models.Book.objects.distinct()
    return HttpResponse("

Query successful!

"
)

filter() The method is based on double-underscore fuzzy queries (the same applies to exclude).

Note:In filter the only operator that can be used is the equals sign = ; you cannot use the greater-than sign > or the less-than sign < , and other symbols.

__in is used to read a range; after the = sign is a list.

Example

from django.shortcuts import render,HttpResponse
from app01 import models
def add_book(request):
    # Query data whose price is 200 or 300
    books = models.Book.objects.filter(price__in=[200,300])
    return HttpResponse("

Query successful!

"
)

__gt Greater-than sign; after the = sign is a number.

# 查询价格大于200的数据 

books = models.Book.objects.filter(price__gt=200)

**__gte** greater than or equal to; after the = sign is a number.

# 查询价格大于等于200的数据 

books = models.Book.objects.filter(price__gte=200)

__lt Less than; after the = sign is a number.

# 查询价格小于300的数据 

books=models.Book.objects.filter(price__lt=300)

__lte Less than or equal to; after the = sign is a number.

# 查询价格小于等于300的数据 

books=models.Book.objects.filter(price__lte=300)

__range Between ..., a closed interval on both ends; after the = sign is a list of two elements.

books=models.Book.objects.filter(price__range=[200,300])

__contains Contains; after the = sign is a string.

books=models.Book.objects.filter(title__contains="菜")

__icontains Case-insensitive contains; after the = sign is a string.

books=models.Book.objects.filter(title__icontains="python") # 不区分大小写

__startswith Starts with the specified characters; after the = sign is a string.

books=models.Book.objects.filter(title__startswith="菜")

__endswith Ends with the specified characters; after the = sign is a string.

books=models.Book.objects.filter(title__endswith="教程")

__year Is the year of a DateField data type; after the = sign is a number.

books=models.Book.objects.filter(pub_date__year=2008) 

__month Is the month of a DateField data type; after the = sign is a number.

books=models.Book.objects.filter(pub_date__month=10) 

__day Is the day of a DateField data type; after the = sign is a number.

books=models.Book.objects.filter(pub_date__day=01)

Delete

Method 1:Use the model class's object.delete()。

Return Value:A tuple whose first element is the number of affected rows.

books=models.Book.objects.filter(pk=8).first().delete()

Method 2: use QuerySet type data.delete()(recommended)

Return Value:A tuple whose first element is the number of affected rows.

books=models.Book.objects.filter(pk__in=[1,2]).delete()

Note:

books=models.Book.objects.delete()  # 报错

books=models.Book.objects.all().delete()   # 删除成功

Modify

Method 1:

模型类的对象.属性 = 更改的属性值

模型类的对象.save()

Return Value:The edited model class object.

books = models.Book.objects.filter(pk=7).first() 

books.price = 400 

books.save()

Method 2:QuerySet type data.update(field_name=changed_data) (recommended)

Return Value:An integer, the number of affected rows

Example

from django.shortcuts import render,HttpResponse
from app01 import models
def add_book(request):
    books = models.Book.objects.filter(pk__in=[7,8]).update(price=888)
    return HttpResponse(books)

- The field name of the parameter must be enclosed in quotes - to get only the data, use values_list