Python3 development of the common operation of ORM in the Advanced-django framework (F-Query and Q-query, transaction)

Source: Internet
Author: User

Read Catalogue

    1. F Query and Q query
    2. Transaction

One, f query and Q Query 1, f query

Pre-query preparation

 class   Product (models. Model): Name  = models. Charfield (Max_length=32 = models. Decimalfield (max_digits=10, Decimal_places=2)  #   inventory = models. Integerfield ()  #   sell number  Sale = models. Integerfield ()  def  __str__   (self):  return   " {}:{}:{}:{}  . Format (Self.name, Self.price, Self.inventory, Self.sale )
models under the app
INSERT  intoApp01_product (ID, name, price, inventory, sale)VALUES(1,'It's getting bigger with Dava .',239, +,Ten);INSERT  intoApp01_product (ID, name, price, inventory, sale)VALUES(2,'with She learn to blow',20150, -, -);INSERT  intoApp01_product (ID, name, price, inventory, sale)VALUES(3,'talk to Sanva and learn to call Michael .',50150, -,0);INSERT  intoApp01_product (ID, name, price, inventory, sale)VALUES(4,'Learn poetry with Shiva',159, -,10000);INSERT  intoApp01_product (ID, name, price, inventory, sale)VALUES(5,'learn the fresh air with five dolls',155, -, $);INSERT  intoApp01_product (ID, name, price, inventory, sale)VALUES(6,'To learn to spit with six dolls .', the, $,1);
SQL data name: main_app01_product

In all of the above examples, the filters we construct simply compare the field values to a constant. What if we were to compare the values of two fields?

Django provides F () to make such comparisons. An instance of F () can reference a field in a query to compare the values of two different fields in the same model instance.

Example 1:

Query for items with a sell number greater than the stock number

From Django.db.models import Fmodels.Product.objects.filter (sale__gt=f (' inventory '))

Django supports subtraction and modulo operations between f () objects and between f () objects and constants.

Models. Product.objects.filter (sale__lt=f (' sale ')

The modify operation can also use the F function, for example, to increase the price of each book by 30 yuan

Models. Product.objects.update (Price=f ("price") +30)

Note: The update modifies fields and objects, and the difference between the property modification fields:

1. Object. Property method Updates all fields

2. The Update method will only update the field you modified.

Extended:

What if you want to modify the Char field?

such as: Add all the titles (first edition)

From django.db.models.functions import concatfrom django.db.models import Valuemodels.Product.objects.update (title= Concat (F ("title"), Value ("("), Value ("first version"), Value (")"))
2, q query

1, multiple query conditions to do intersection and set the inverse operation

2, if the Q query and keyword query exist at the same time, Q query to be placed in front of the keyword query

The keyword parameter queries in methods such as filter () are all "and" together. If you need to perform more complex queries (such as an OR statement), you can use the Q object .

Example 1:

Query sell number is greater than 100 or the price is less than 100

Models. Product.objects.filter (Q (sale__gt=100) | Q (sale__lt=100))

You can combine & and | Operators and use parentheses to group them to write arbitrarily complex Q objects. at the same time, theQ object can be reversed using the ~ operator, which allows the combination ofnormal query and inverse (not) queries.

Example: a product that queries that the stock count is 100 and the sell number is not 0

Models. Product.objects.filter (Q (inventory=100) & ~q (sale=0))

Query functions can be mixed using the Q object and the keyword parameters. all arguments (keyword arguments or Q objects) that are provided to the query function are "and" together. However, if the Q object appears, it must precede all the keyword parameters.

For example: Query product name contains spit, and inventory number is greater than 60

Models. Product.objects.filter (Q (inventory__gt=60), name__icontains= "spit")
Second, the business

1. What is a transaction?

Atomicity, isolation, persistence, consistency of data

classProduct (models. Model): Name= Models. Charfield (max_length=32) Price= Models. Decimalfield (max_digits=10, decimal_places=2)    #Number of stocksInventory =models. Integerfield ()#Sell numbersale=models. Integerfield ()def __str__(self):return  "{}:{}:{}:{}". Format (Self.name, Self.price, Self.inventory, Self.sale)classOrder (models. Model): Num= Models. Charfield (max_length=64) Product= Models. ForeignKey (to="Product") Count= Models. Integerfield ()
classes in the models
INSERT into app01_product (ID, name, price, inventory, Sale) VALUES (1,'It's getting bigger with Dava .', 239, 1000, 10INSERT into app01_product (ID, name, price, inventory, sale) VALUES (2,'with She learn to blow', 20150, 60, 60INSERT into app01_product (ID, name, price, inventory, sale) VALUES (3,'talk to Sanva and learn to call Michael .', 50150, 100, 0); INSERT into app01_product (ID, name, price, inventory, sale) VALUES (4,'Learn poetry with Shiva', 159, 50, 10000INSERT into app01_product (ID, name, price, inventory, sale) VALUES (5,'learn the fresh air with five dolls', 155, 100, 200INSERT into app01_product (ID, name, price, inventory, sale) VALUES (6,'To learn to spit with six dolls .', 152, 200, 1);
SQL Data Main_app01_product
 import osif __name__ = = ' __main__ ': Os.environ.setdefault ("Django_settings_module", "bms.settings") Import Djan         Go django.setup () import datetime from APP01 Import models try: 
from django.db.models import F From django.db Import transaction
#买一本书
#在数据库层面要做到的事儿
#1, create an order data
#2, go to the product table to sell Number +1, Stock count-1 with transaction.atomic (): #开启事务处理
#创建一条订单数据
models. Order.objects.create (num= ' 123456789 ', product_id=1,count=1)
#去产品表 sell number +1, stock 1 (Error)
models. Product.objects.get (id=1). Update (inventory=f (' Inventory ') -1,sale=f (' sale ') +1)
#能执行成功
#model S.product.objects.filter (id=1). Update (inventory=f (' Inventory ' -1,sale=f (' sale ') +1))
except Exception as E:
P Rint (e)

# Do not open transactions
# try:
# # Create an order data
# models. Order.objects.create (num= "123456789", Product_id=1, Count=1)
# go to Product table will sell number +1, in stock-1
# models. Product.objects.get (id=1). Update (Kucun=f ("Kucun")-1, Maichu=f ("Maichu") + 1)
# except Exception as E:
# print (E)

Python3 development of the common operation of ORM in the Advanced-django framework (F-Query and Q-query, transaction)

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.