Python Learning---Django orm additions and deletions 180125

Source: Internet
Author: User

field type parameters commonly used by the model

<1> Charfield
#字符串字段, used for shorter strings.
#CharField requires a parameter, maxlength, to limit the maximum number of characters allowed for this field from the database tier and the Django check layer.
<2> Integerfield
#用于保存一个整数.
<3> Floatfield
# A floating-point number. Two parameters must be supplied: description of parameters
# Total digits of max_digits (excluding decimal points and symbols)
# decimal_places number of decimal digits
# For example, to save a maximum value of 999 (save 2 digits after the decimal point), you would define the field as follows:
# models. Floatfield (..., max_digits=5, decimal_places=2) # total 5 bits, where 2 bits are decimals
# to save the maximum value of 1 million (save 10 digits after the decimal point), you should define this:
# models. Floatfield (..., max_digits=19, decimal_places=10) # Total 19 bits, where 10 bits are decimals
# Admin uses a text box (<input type= "text" >) to represent the data that the field holds.
<4> Autofield
# a Integerfield, it will grow automatically when you add a record. You do not usually need to use this field directly;
# Customize a primary key: My_id=models. Autofield (Primary_key=true)
# If you do not specify a primary key, the system will automatically add a primary key field to your model.
<5> Booleanfield
# A true/false field. The admin uses a checkbox to represent such fields.
<6> TextField
# A text field with a large capacity.
# Admin uses a <textarea> (text area) to represent the field data. (a multi-line edit box).
<7> Emailfield
# a charfield,py3 with check email legitimacy supports maxlength parameters. Py2 not supported
<8> Datefield
# a Date field. There are the following additional optional parameters:
# Argument Description
# Auto_now When an object is saved, the value of the field is automatically set to the current time. Typically used to represent a "last-modified" timestamp.
# Auto_now_add When an object is first created, the value of the field is automatically set to the current time. Typically used to represent object creation time.
# (meaning only in admin ...)
<9> Datetimefield
# A date-time field. Similar Datefield support the same additional options.
<10> ImageField
# similar to Filefield, but verify that the uploaded object is a legitimate picture. #它有两个可选参数: Height_field and Width_field,
# If you provide these two parameters, the picture will be saved according to the provided height and width specifications.
<11> Filefield
# A File Upload field: Requires a required parameter: upload_to,
# upload_to: A local file system path to save the uploaded file. This path must contain strftime#formatting, which will be replaced with the date/time of the uploaded file (so uploaded files don ' t fill up the given directory).
# Admin with a <input type= "file" > part represents the data saved by the field (a file upload part).
Note: Using Filefield or ImageField in a model requires the following steps:
# (1) in your settings file, define a full path to media_root so that Django can save the uploaded file here.
# (For performance reasons, these files are not saved to the database.) Defines media_url as the public URL for this directory. To make sure that the directory
# Web server user account is writable.
# (2) Add Filefield or ImageField to your model and make sure the UPLOAD_TO option is defined to tell the Django
# which subdirectory of Media_root is used to save the uploaded file. The path to the file in your database (relative to Media_root).
# Out of habit you must be very interested in using Django-provided get_< #fieldname >_url functions. For example, if your ImageField
# called Mug_shot, you can get the absolute path of the image in the template in the same way as {{Object #get_mug_shot_url}}.
<12> Urlfield
# used to save URLs. If the verify_exists parameter is True (the default), the given URL is pre-checked for presence (that is, if the URL is loaded effectively and
# no return 404 response).
# Admin with a <input type= the "text" > text box represents the data saved by the field (a single-line edit box)
<13> Nullbooleanfield
# similar to Booleanfield, but allow NULL as one of the options. It is recommended to use this field instead of the Booleanfield plus null=true option
# Admin uses a selection box <select> (three selectable values: "Unknown", "Yes" and "No") to represent this field data.
<14> Slugfield
# "Slug" is a newspaper term. Slug is a small mark (a short sign) of something that contains only letters, numbers, underscores, and hyphens. #它们通常用于URLs
# If you use the Django development version, you can specify MaxLength.  If MaxLength is not specified, Django will use the default length: 50. #在
# previous Django version, there is no way to change the length of 50.
# It's a hint of db_index=true.
# It takes an extra parameter: Prepopulate_from, which is a list of fields from which to auto-#populate
# The Slug, via javascript,in the object ' s admin form:models. Slugfield
# (Prepopulate_from= ("Pre_name", "name") Prepopulate_from does not accept datetimefields.
<13> XMLField
#一个校验值是否为合法XML的 TextField, you must provide the parameter: Schema_path, which is a Relaxng schema #的文件系统路径 used to verify the text.
<14> Filepathfield
# Optional items are file names under a specific directory. Three special parameters are supported, the first of which is the one that must be provided.
# parameter Description
# path required parameter. The absolute file system path of a directory. Filepathfield the optional items accordingly.
# Example: "/home/images".
# Match Optional parameters. A regular expression, which, as a string, Filepathfield uses to filter the file name.
Note that this regular expression will only be applied to base filename instead of
# Path full name. Example: "foo.*\.txt^" will match the file Foo23.txt but does not match bar.txt or foo23.gif.
# Recursive optional parameters. Either True or False. The default value is False. Whether to include all subdirectories below path.
# These three parameters can be used at the same time.
# Match applies only to base filename, not to the path full name. So, this example:
# Filepathfield (path= "/home/images", match= "foo.*", Recursive=true)
# ... Matches/home/images/foo.gif and does not match/home/images/foo/bar.gif
<15> Ipaddressfield
# an IP address in the form of a string (i.e. "24.124.1.30").
<16># Commaseparatedintegerfield
# used to hold comma-separated integer values. Similar to Charfield, there must be maxlength parameters.

Field Important parameters

<1> null: Whether the field in the database can be empty
<2> whether null values are allowed when adding data in the Admin of Blank:django
<3> Default: Set defaults
<4> Editable: If False, admin mode will not overwrite. Default is True
<5> Primary_key: Sets the primary key, which is automatically added if the Django creation table is not set:
id = meta. Autofield (' ID ', primary_key=true)
Primary_key=true implies Blank=false, Null=false and Unique=true. Only one
Primary key is allowed in an object.
<6> Unique: Data unique
<7> verbose_name admin in the display name of the field
<8> validator_list: Validity check. Non-efficient generation of django.core.validators.ValidationError errors
<9> Db_column,db_index If you create an index for this field
<10>choices: A 2-dimensional tuple that is used to select values. The first value is the actual stored value, and the second is used to make the selection easier.
such as sex_choices= (' F ', ' Female '), (' M ', ' Male '),)
Gender = models. Charfield (max_length=2,choices = sex_choices)

table operation of the increase and deletion check 2018-01-25 08:20/2018-01-27 17:33

Table Operation Increase--------------Create,save

Increase of single table operation

views.py

From blog.models import bookfrom blog.models import publishfrom blog.models import authorfrom blog.models import Authordet Aildef Createauthor (Request):    # Create mode one:     Author.objects.create (**{' name ': ' FTL '}) # using a dictionary, recommended    # Create mode two:     Author.objects.create (name= "FTL")      # Save mode one:      Author = Author (name= ' FTL ')                        Author.save ()    # Save Mode II:      Author1 = Author ()                         author1.name = ' FTL '                         author1.save ()

Multi-table operation increased---one-to-many

views.py

# one-to-many, foreign-key table insert [foreign key on the more side to create]def Createbook (Request):    # Method: Create Book.objects.create with the table ID    (        title= ' Python ',        price=100,        page_num=100,        author_id=1,  # here 1 means that the book object is bound to the Id=1 row object in the Authorr table        publish_id=1, # Here 1 means that the book object is bound to the Id=1 row object in the Publisher table        publish_date= ' 2020-01-01 ',    )    # Way two: Using object creation    Author1 = Author.objects.get (id=2)    publish1 = Publish.objects.get (id=2)    Book.objects.create (        title= ' Java ',        price=90,        page_num=100,        Author=author1,   # This is the object we created when we built our own tables. The Id=1 object        in the Authorr table obtained by get is bound PUBLISH=PUBLISH1,  # here 1 means that the book object is bound to 1 objects in Publisher table Id=1        publish_date= ' 2020-02-02 ',    )

Multi-table Operation---Many-to-many, Many2many create a third-party table, but the ORM layer can not create such operations [can be placed any object]

Forward query:

# Many-to-many, can only be bound by object # Forward Query Author2 = Author.objects.get (id=3) Author3 = Author.objects.filter (name= ' FTL ') [0]  # Returned is a author object book2 = Book.objects.get (id=1) book2.author.add (Author2, Author3)    # Add 2 author objects to the author property of the instantiated Book2 object #book2.author.remove (Author2, Author3) # delete 2 Book2 objects for the author property of the instantiated author object # Book2.author.add (*authors)  # Authors for instantiated Book2 objects "Author is a list, must take * value" # equals to use list [Add *]:book2.authors.add (*[ Author2, Author3])  # Here is the list object ha book2.authors.remove (*[author2, Author3])
Reverse query:
# Reverse Query [author field is defined in book, so you can bind the object according to the author property inside the book]
# [Reverse is derived from the class name lowercase, eg book-to BOOK]BOOK3 = Book.objects.filter (id_gt=1)  # Here is the collection, Uauthor4 = Author.objects.filter ( id=1) [0]# finds the author attribute in book according to Book_set, then adds Add () Author4.book_set.add (*BOOK3)         # Note Add * [Here the book is the class book replaced by lowercase, fixed usage]# Author4.book_set.remove (*BOOK3)    # Note Add * [Here the book is the class book replaced by lowercase, fixed usage]#------------------------------------------ -----------------Book3.author.add (1) book3.author.remove (1) author4.book_set.add (1) author4.book_set.remove (1)

Multi-table Operations---Create a third-party table yourself

/blog/models.py

#     If you create a third relationship table, set the relationship between the third table and the other 2 tables [foreign key Settings]:class Book2author (models. Model):      author =models. ForeignKey ("Author")  # You are my foreign key, and I am your foreign key book      =  models. ForeignKey ("book")    # You are my foreign key, and I am your foreign key #     creating Author,book instantiated object      author_obj= models. Author.objects.filter (id=2) [0]      book_obj  = models. Book.objects.filter (id=3) [0]      s=models. Book2Author.objects.create (author_id=1,book_id=2)  # B2A Object Add Data      s.save ()      s=models. Book2author (author=author_obj,book_id=1)  # B2a object property Assignment A B/a object       s.save () #     defines the attribute      class Meta:                                  Unique_together (' author ', ' book ')   # [Union Unique]

Deletion of single-table operation [first check and delete]--------------delete,remove,clear

Deletion of single-table operation---Cascade delete of single table [Django default is cascade deleted]

# Delete Mode One: Filter information after query information remove delete () >>> Book.objects.filter (id=1). Delete () (3, {' App01. Book_authors ': 2, ' app01. Book ': 1})

Deletion of single-table operation---Many-to-many tables

Forward Delete:

Book_del = Book.objects.filter (id=1)  # finds the book object to delete Book_del.author.clear ()    # Clears all data associated with id=1 in book Book_ Del.author.remove (2)  # Delete all data with author attribute id=2 in book Book_del.author.remove (*[1, 2, 3, 4])  # can be a list, preceded by *

Reverse Delete:

Author = models. Author.objects.filter (id=1)  #  Find id=1 authorauthor.book_set.clear ()  # Empty all data associated with id=1 in book

Change of table operation [first check and then change]--------------Update,save

Modification of single-table operation

# Way One: Save () Book_update = Book.objects.get (id=1)  # Find the book object of the id=1 to update = ' C + + ' # Modify the title content of this object Book_update.save () # Method two: Fileter (). Update ()   recommended to use Book.objects.filter (id=1). Update (title= ' C + + ') # Update the contents of the title of the Id=1 book object

Attention:
1, the way a get returned is a model object, it does not have the Update method
Mode two filter returns a Queryset object [a heap of collections],update is a method of Queryset objects
(The condition in filter may have multiple conditions, such as Name= ' Alvin ', there may be two name= ' Alvin ' rows of data)
2, the way a Save method will be all the properties [all columns in the data] re-set again, inefficient
Mode two Update method directly set corresponding properties, high efficiency
3, mode two The return result of the Update method is an integral type, which is the number of times the database was modified

Change of multi-table operation

obj = Book.objects.filter (id=1) [0]author = Author.objects.filter (id__gt=2) obj.author.clear () Obj.author.add (*author )

Table Operation Check--------------Filter,value, etc.

Query API for single-table operations

#  <1>filter (**kwargs):      It contains the object "collection Object" # <2>all () that matches the given filter  criteria:                 Query All Results "collection Object" #  <3 >get (**kwargs):         Returns an object that matches the filter criteria given, with the result that there is only one "single object"                             if more than one object that meets the filter criteria or not will throw an error.

Re-processing of query results for single-table operation

#-----------The following methods are used to process the results of the query: for example, Objects.filter.values ()--------# <4>values (*field): Returns a valuequeryset-- A special queryset "iterative dictionary sequence" that is an instantiated object of the model, is an iterative dictionary [{' name ': ' FTL '},{' title ', ' Python '},]title = book.objects . Filter (id=2). VALUES (' title ') # <5>exclude (**kwargs): It contains objects that do not match the given filter criteria # &L            T;6>order_by (*field): Sort the results of the query Book.objects.order_by ("-id") # Note here is the reverse sort operation using the minus sign # <7>reverse (): Reverse order of Query Results # &LT;8&GT;DISTINCT (): Remove duplicate records from returned results # <9>values_list (*field): It is very similar to values (), it returns a tuple sequence, values Returns a dictionary sequence # <10>count (): Returns the number of objects in the database that match the query (QuerySet). # <11>first (): Returns the first record # <12>last (): Returns the last Record # <13>exists (): If Que                              Returns True if the Ryset contains data, otherwise false is returned. if exists ():

Extended query with single table operation

#扩展查询, sometimes the Django query API is not easy to set up the query conditions, providing an additional way to expand the query Extra: #extra (Select=none, Where=none, Params=none, Tables=none,order  _by=none, Select_params=none (1) Entry.objects.extra (select={' is_recent ': "Pub_date > ' 2006-01-01 '"}) (2) Blog.objects.extra (Select=sorteddict ([' A ', '%s '), (' B ', '%s ')]), select_params= (' One ', ' ') ') (3) q = Ent Ry.objects.extra (select={' is_recent ': "Pub_date > ' 2006-01-01 '"}) Q = Q.extra (order_by = ['-is_recent ']) (4) Entry. Objects.extra (where=[' headline=%s '), params=[' Lennon ']) Note 1: If there are data modifications between the 2 operations, you need to re-check the values from the database, or Django will take the data out of the cache.    Affects the final query result. # objs=models.    Book.objects.all () # [obj1,obj2,ob3 ...] # for Obj in Objs: # Each obj is a row object that executes SQL # print ("obj:", obj) Models.Bool.update.get (id=2). Update (' Title ' = ' YYY ') # Changes within the database, the cache has not changed # Objs=models. Book.objects.all () Re-finds and assigns values from the database to objs# objs.update (title= ' YYY ') is recommended, the direct database/memory has changed, the following for loop query re-executed the database # Objs=models.    Book.objects.all () # [obj1,obj2,ob3 ...]    # for obj in OBJS:             # print ("obj:", obj) # or Objs object, so the value from the cache is correctly manipulated: 1. Re-executes the query objs=models. Book.objects.all () "Not recommended" 2.  Using Objs.update (title= ' YYY '); At this point the database has changed and the values in the cache have been changed note 2:if OBJS (): Queries the database and puts all the data results of the query into the database if Objs.exist (): Queries the database only, but does not put all the data in the database, I F Obj.iterator (): Data is put into an iterator, once in one iteration

Set operation log of table operation

LOGGING = {    ' version ': 1,    ' disable_existing_loggers ': False,    ' handlers ': {        ' console ': {            ' level ': ' DEBUG ',            ' class ': ' Logging. Streamhandler ',        },    },    ' loggers ': {'        django.db.backends ': {'            handlers ': [' console '],            ' Propagate ': True,            ' level ': ' DEBUG ',        },    }} another: obj = Book.objects (). VALUES (' Publish_name ') print ( obj.query)     # Print Query sql

Python Learning---Django orm additions and deletions 180125

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.