Operation of the database (CRUD operations)

Operation of the database (CRUD operations)

  CRUD refers to an increase in the time to do the calculation processing (create), read queries (read) and update (update), and delete (delete)

A manager object

1. Each model class inherits from modelss.Model, there will be a similar object is inherited objects. This object is called additions and deletions to the database manager object 2. The change search can be achieved by the model manager

class the Entry (models.Model): 
    ... 
Entry.objects.create (...) # is the manager object

Two create data objects

Django uses an intuitive way to represent the data in a database table as Python object

Creating data in each record is to create a data object

1.Entry.objects.create (attribute values ​​1 = 1, attribute value = 1 2, ...)

  Success: Returns the created entity object

  Failure: throw an exception

2. Create Entry entity object and call save () to save

obj = Entry (property = value property = value) 
obj. attribute = value 
obj.save () 
does not return a value, after the success of preservation, obj will be reassigned
the try : 
    abook = Book.objects.create (title = ' Python ' , Pub = ' Tsinghua University Press ' )
     Print (abook)
 the except :
     Print ( " Failed to create object ' )
Example 1
the try : 
    abook = Book (title = ' Python ' , Pub = ' Tsinghua University Press ' ) 
    abook.save 
    Print (abook)
 the except :
     Print ( " Failed to create object ' )
Example 2
the try : 
    abook = Book () 
    abook.title = ' Python ' 
    abook.pub = ' Tsinghua University Press ' 
    abook.save 
    Print (abook)
 the except :
     Print ( " Failed to create object ' )
Example 3

Three using Django shell of

  In Django is to provide an interactive operation of a project called Django Shellits ability to perform the corresponding operation in interactive mode with the project code

  Django Shell may be replaced using code written to operate directly See

  Simple operation only at Django Shell, can not be run remotely modal

  Start Django shell IPython-style interface displays the following:

$ python3 manage.py shell
manage.py shell
Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: 
In [2]: from bookstore import models
In [3]: models.Book.objects.create(title="Python")
Out[3]: <Book: Book object>
In [4]: book = models.Book.objects.create(title='C++')
In [4]: print(book)
Book object

Four query data

  Query the database manager needs to use objects

  Call to query interface method by Entry.objects Manager

method

usage

effect

return value

all()

Entry.objects.all()

Data Entry query all entities

QuerySet container object instance stored internally Entry

values ​​( 'column 1', 'Column 2')

Entry.objects.values(...)

Query and returns the data portion of the column

Selected from xxx column 1, column 2

QuerySet

Return query results container, container memory dictionary, each representative of a data dictionary,

Format: { 'Column 1': the value of 1, 'Column 2': 2} values

values_list ( 'column 1', 'Column 2')

Entry.objects.values_list(...)

Return query results in the form of tuples

QuerySet container object, stored internally元组

Package will check out the data to the tuple, and then encapsulating in the query set QuerySet

ORDER_BY

Entry.objects.order_by( ' - 列', '列')

And all () methods, it will query results using ORDER BY clause of a SQL statement based on a selective sort field

Note: The default is sorted in ascending order, in the descending order need to increase before the column '-' indicates

 

filter (condition)

Entry.objects.filter (attribute values ​​1 = 1, attribute value = 2 2)

According to conditions of the query multiple records

QuerySet container object instance stored internally Entry

 

# Find all 
from child of the bookstore Import Models 
Books = models.Book.object.all ()
 for Book in Books:
     Print ( " title " , book.title, ' Press: ' , book.pub) 

# ##### ################ 

# returns the specified column (Dictionary represented) 
from child of the bookstore Import Models 
Books = models.Book.objects.values ( " title " , " Pub " )
 for Book in books:
    Print ( " title " , Book [ " title " ], ' Publisher: ' , Book [ ' Pub ' ])
     Print ( " Book = " , Book) 

# ############# ######### 

# returns the specified column (tuple representation) 
from child of the bookstore Import Models 
Books = models.Book.objects.values_list ( " title " , " Pub " )
 for Book in Books:
     Print (" Book = " , Book)   # ( 'Python', 'Tsinghua University Press') ... 

# ###################### 

# sort queries 
from child of the bookstore Import Models 
Books = models.Book.objects.order_by ( " . price " )
 for Book in Books:
     Print ( " title: " , book.title, ' prices: ' , book.price) 

# ###### ################ 

# accordance with the conditions query multiple records 
# 1. inquiry Press for the book "Tsinghua University Press"Books 
from child of the bookstore ImportModels 
Books = models.Book.objects.filter (Pub = " Tsinghua University Press " )
 for Book in Books:
     Print ( " title: " , book.title) 

# 2. query Author of the id entity and isActive to 1 True the 
    authors = Author.objects.filter (id = 1, isActive = True)
Example shows

Model defined in the class def __str__(self):methods can be custom default string

class Book (models.Model): 
    title = ...
     DEF  __str__ (Self):
         return  " Title:% s, Publisher:% s, price:% S " % (self.title, self.pub, Self. price)

Find five field

Six query predicate

Seven modify the data record

Eight delete records

Nine aggregate query

F object

Object Q - Q ()

Native database operation method

# By 

# models.Tb1.objects.create (= C1 'XX', C2 = 'OO') add a data type of the data dictionary can accept kwargs ** 

# obj = models.Tb1 (= C1 'XX', C2 = 'OO') 
# obj.save () 

# check 

# models.Tb1.objects.get (ID = 123) obtaining a single data error does not exist (not recommended) 
# models.Tb1.objects.all () Get all 
# models.Tb1.objects.filter (name = 'seven') acquires a specified condition data 

# puncturing 

# models.Tb1.objects.filter (name = 'seven'). delete () delete data specified condition 

# change 

# Models. Tb1.objects.filter (name = 'Seven'). update (Gender = '0')    
# the updated data specified condition, support kwargs ** 
#= models.Tb1.objects.get obj (= ID. 1) 
# obj.c1 = '111' 
# obj.save () # single modified data
Basic CRUD operations

 

Guess you like

Origin www.cnblogs.com/maplethefox/p/11235412.html