F Django's query Q query, things

       Query F

  Django provides F () to do such a comparison. Examples F. () Can be referenced in the query field, the value to compare different fields of the same model example two

  

Example 1:

 

Check out the inventory number is greater than the number sold goods

 

from django.db.models import F
ret1=models.Product.objects.filter(maichu__gt=F('kucun'))
print(ret1)

 

F can help us get to the table a field corresponding values ​​as my filter criteria, rather than I think a custom constant conditions, and to achieve a dynamic comparative results

 

Django supports F (, and () operation between the object and the addition, subtraction modulo F constant and between objects). This may be based on mathematical operations of numerical type table

 

The price of each product rises 50

 

models.Product.objects.update(price=F('price')+50)

 

Extended:

 

If you want to modify char field supposed to (do not spend the face value of the type of operation !!!)?

 

Such as: the title plus all subsequent 'new', (time required for this string Concat splicing operation, and to add value splicing Value)

 

from django.db.models.functions import Concat
from django.db.models import Value
ret3=models.Product.objects.update(name=Concat(F('name'),Value('新款')))

 

Concat representation splicing operation, the parameters of the string determines the splicing head or splicing in the tail splicing, Value which is spliced ​​to the new value

 

1 | 2 Q query

 

filter ()  method such as comma-separated relationship with the proviso that. If you need to perform more complex queries (such as OR statements), you can use Q objects .

 

Example 1:

 

100 sold query number is greater than or less than the price of 100

 

from django.db.models import Q
models.Product.objects.filter(Q(maichu__gt=100)|Q(price__lt=100))

 

Q when a layer of wrapped condition, filter and to support cross Comparison operators

 

Example 2:

 

Query inventory number is 100 and the number of sold products is not 0

 

models.Product.objects.filter(Q(kucun=100)&~Q(maichu=0))

 

We can combine &  and |   operators and written using parentheses grouped arbitrarily complex Q  object.

 

Meanwhile, Q  objects can ~  be negated, which allows a combination of normal and inverted query ( the NOT ) query.

 

Example 3:

 

The new product name contains the query, and inventory number is greater than 60

 

models.Product.objects.filter(Q(kucun__gt=60), name__contains="新款")

 

Query function can mix Q objects and keyword arguments. All parameters (or keyword arguments provided to the query function Q  objects) are "AND" together. However, if there is Q  objects, it must precede all keyword arguments.

Specific methods of the column:

 # Commodity number of inquiries sold more than 50 of the 
    # RES = models.Product.objects.filter (maichu__gt = 50) 
    # Print (RES) 
    # inquiry number is greater than the number of stock sold goods 

    # from django.db.models Import F, Q 
    # F. Discover 
    # RES = models.Product.objects.filter (maichu__gt = F. ( 'kucun')) 
    # Print (RES) 
    # will increase the price of all the items 100 
    # from F. django.db.models Import, Q 
    # models.Product.objects.update (. price = F. ( '. price') + 100) 
    # the names of all products back plus a burst section 
    # from django.db.models.functions Import Concat 
    # from django.db.models Import Value 
    #models.Product.objects.update (name = Concat (F ( 'name'), Value ( ' Cleavage'))) 

    # Q query 
    # RES = models.Product.objects.filter (= 188.88. price, name = 'Dress Cleavage ') 
    # Print (RES) 
    # from F. django.db.models Import, Q 
    # RES = models.Product.objects.filter (Q (= 188.88. price), Q (name =' dress Cleavage ')) # and 
    # RES = models.Product.objects.filter (Q (. price = 188.88) | Q (name = 'dress burst models')) # or 
    # RES = models.Product.objects.filter (Q (. price = 188.88) | ~ Q (name = 'dress Cleavage')) # Not 
    # mix Q Note that the object must be placed in front of the ordinary filter condition 
    # RES = models.Product.objects.filter (~ Q (name = 'burst dress money '),. price = 188.88) not # 
    # Print (RES)

 

For Q objects added:

 # Q Object complement (******) 
    # from F. Django.db.models Import, Q 
    # Q = Q () 
    # q.connector = 'or' # Q by this parameter and the object may be a default relationship becomes into or 
    # q.children.append (( '. price', 188.88)) 
    # q.children.append (( 'name', 'high-heeled shoes burst models')) 
    # RES = models.Product.objects.filter (Q) # Q is the default object query and 
    # Print (RES)

 

Transaction:

The definition of the transaction: a plurality of operating sql statement into atomic operation, either while successful, a failure which is rolled back to the original state, to ensure the integrity and consistency of the data (for the NoSQL database transaction is supported portion)

Transaction ACID (atomicity, consistency, isolation, durability) 
code is as follows:
    # From django.db Import Transaction 
    # from django.db.models Import F 
    # with transaction.atomic (): 
    #      # write your affairs operations with pieces of code 
    #      models.Product.objects.filter (the above mentioned id = 1). Update (kucun = F. ( 'kucun') -. 1) 
    #      models.Product.objects.filter (= ID. 1) .Update (maichu = F. ( 'maichu') +. 1) 
    #
     # # write additional code logic 
    # Print ( 'hahah')

First, the four characteristics of the transaction (ACID)

If you claim to operate a database supports transactions, then the database must have the following four characteristics:

1, atomicity (Atomicity)

  Atomicity refers to all operations in the transaction included either all succeed, or all fail rolled back, the operator of the transaction if successful, it must be fully applied to the database if the operation fails it can not have any impact on the database.

2. Consistency (Consistency)

  Consistency means that the transaction must transform the database from one consistent state to another consistent state, that is to say before and after a transaction execution and implementation must be in a consistent state.
  Take transfers, if both user A and user B money add up to a total of 5,000, no matter how transfers between A and B, turn several accounts, after the end of the transaction the money add up to two users should have 5000, which is transactional consistency.

3, isolation (Isolation)

  Isolation when a plurality of users concurrent access to the database, such as when operating with a table, a database for each user transaction open, operation not being disturbed by other transactions, for isolation between a plurality of concurrent transactions.
  That is, to achieve such an effect: for any two concurrent transactions T1 and T2, T1 appears in the transaction, T2 or T1 has ended before the start, or started after the end of T1, so each transaction does not feel there are other matters to performing concurrently.

4, persistent (Durability)

  Persistence means that once a transaction is committed, then changes to the data in the database is permanent, commit the transaction will not be lost even in the case of a database system experienced a failure of the operation.
  For example we use JDBC database operations, after the transaction is committed method, the user is prompted transaction is complete, when we complete the program execution until prompted, you can identify and correct the transaction submitted,
even if this time the database there is a problem, it must To complete the full implementation of our business, otherwise it will cause us to see the prompt completion of the transaction, but because of the failure of major database without executing a transaction error.

Transaction isolation level (the default transaction level is repeatable read)

Four kinds MySQL database transaction isolation level

Read Uncommitted (Uncommitted read the content)

Read Committed (read submission)

Repeatable Read (can be re-read)

The Serializable (serializable) 

Second, the transaction isolation level (the default transaction level is repeatable read)

Generally speaking, nothing more than a database transaction in two ways: read transaction (select), modify transaction (update, insert). In the absence of transaction isolation control multiple transactions at the same time operations on the same data might affect the final desired result, there are usually four cases:
(1) two update transaction also modify a data, it is clear this situation is most serious, the program in any case can not happen, because it would result in the loss updated!
(2) an update transaction updates a data read another transaction reads the update has not submitted will be read to the dirty data in this case.
(3) When a read transaction reads a data, another update transaction modifies this data, then there will not be reproducible reading.
(4) a read transaction reads another insert transaction (note inserted here) insert a new data so that it is possible to read out a data appear phantom reads.
Four cases described above is completed, I believe we have found the law, the first three are concurrent operations on the same data, the results of the program may have fatal impact, especially in the financial and other real-time, high accuracy requirements of the system, will not allow the emergence of these three cases,
compared to the fourth case does not affect the authenticity of the data, in many cases, it is allowed, such as social forums, less demanding real-time systems!
: Fully four cases, we can approximate such a simple understanding (consisting of a combination of two of said first transaction of 2 * 2 = 4)
allow to modify (update lost) when A) modified
to allow read when B) modified (dirty read )
allows modification (non Repeatable read) when C) is read
D) permit insertion (phantom read) when the read
from top to bottom increasingly serious problem, but has greater performance overhead required. Because the system allows different circumstances at different levels, so there have been such a transaction isolation stuff, we set to allow concurrent behavior database.

Under summary of the types of problems if we do not consider a transaction isolation will occur:

1, dirty reads
  dirty read transaction refers to a process in a read data transaction in another uncommitted.
  When a transaction is a data modified several times, but this many times in this transaction changes are not committed, then a concurrent transactions to access the data, it will cause inconsistencies two transactions resulting data. For example: a user A to a user B 100 transfers million, corresponding to the following SQL commands
    update account set money = money + 100 where name = 'B'; ( case A notifies B)
    Update Money = Money Account SET - 100 WHERE name = 'A ';
  when performing only the first SQL, a view account notification B, B found that indeed the money has been credited into account (which happened at this time the dirty read), but after the second SQL regardless of whether or not to perform, as long as the transaction is not submitted, all operations are rolled back, then when B after viewing the account again you will find the money, it did not turn.

2, non-repeatable read
  non-repeatable read means for the data of a database, a transaction within the scope of the multiple queries has returned different data values, which is due to poll interval is modified and submitted to another transaction.
  For example, a read data transaction T1, T2 and immediately modify the transaction data and the transaction submitted to the database, transaction T1 the data is read again obtained different results, the non-repeatable read transmission.
  Repeating the reading and non-reading difference is dirty, is a dirty read transaction reads dirty data from another uncommitted transaction, and can not repeat the reading of data is read before a transaction commits.
  In some cases, non-repeatable read is not a problem, such as we have repeatedly query a data query of course, to get the final result based. But there may occur in other cases the problem, for example, may be different for the same data A and B in turn queries, A and B can play up ......

3, dummy read (phantom read)
  Magic Reading is a phenomenon that occurs when a transaction non-independent execution. For example, transaction T1 to a data item in a table of all the lines made from "1" to "2" in the operation, but this time the value of the table row is inserted into a data item, the data item and the transaction T2 or "1" and committed to the database. The operations of the transaction T1 users to see if we just modify the data, you will find there is a line not modify, in fact, this line is added from the transaction T2, like hallucinations, like, this is what has happened phantom reads.
  Phantom reads and non-repeatable read are read another transaction has been submitted (this is different to dirty read), the difference is non-repeatable read query data items are the same, but the magic of reading for a group overall data (such as the number of data).

 SQL standard defines four types of isolation levels, including a number of specific rules, which defines changes to internal and external transaction is visible, which is not visible. Low levels of isolation generally support higher level of concurrent processing, and have lower overhead.

Four kinds MySQL database transaction isolation level

Read Uncommitted (Uncommitted read the content)

       In this isolation level, all transactions can see the results of other uncommitted transactions. This isolation level is rarely used in practice, because its performance is not much better than the other levels. Uncommitted read data, also called a dirty read (Dirty Read);

Read Committed (read submission)

       This is the default isolation level for most database systems (MySQL, but not the default). It meets the simple definition of isolation: a transaction can only see the change has been submitted firms do. This isolation level also supports so-called non-repeatable read (Nonrepeatable Read), because other instances of the same transaction in the example of the process during which there may be a new commit, so select the same may return a different result;

Repeatable Read (can be re-read)

       This is the default MySQL transaction isolation level, it ensures that the same transaction multiple concurrent instances when data is read, it will see the same data row. But in theory, it will lead to another thorny issue: Magic Reading (Phantom Read).
       Simply put, phantom read means that when a user reads a range of data row, another transaction and insert a new row within the range, when the user re-read the range of data rows, you will find a new " Phantom "line.
       InnoDB and Falcon storage engine through a multi-version concurrency control (MVCC, Multiversion Concurrency Control) mechanism to solve the problem

The Serializable (serializable) 

       This is the highest level of isolation, it is forced to sort through the transaction, making it impossible to conflict with each other, so as to solve the problem phantom read. In short, it is to add a shared lock on each row of data read. At this level, it could lead to a lot of timeouts and lock contention.
         The four isolation levels to take a different type of lock is achieved, if the same data is read, then it is prone to problems. E.g:

         Dirty read (Drity Read): a transaction has been updated copy of the data, another transaction at this time to read the same data, for some reason, before a RollBack operation, the firm after a data read on It would be incorrect.
         Non-repeatable read (Non-repeatable read): In two inquiries into a transaction data is inconsistent, which may be inserted into the middle of the query process twice the original data in a transaction update.
         Magic Reading (Phantom Read): Two query data items in a transaction not, for example, there is a transaction query the columns (Row) data, while another transaction but at this time insert new columns of data, previously transaction in the next query, you will find there are several columns of data that it previously did not have.
         In MySQL, four isolation levels achieved, respectively, a problem may arise as follows:
         
         
  ① the Serializable (serialization): can prevent dirty reads, non-repeatable read, phantom read occurs.
  ② Repeatable read (Repeatable Read): can prevent dirty reads, unrepeatable reads occurring.
  ③ Read committed (Read Committed): can avoid dirty reads to occur.
  ④ Read uncommitted (read uncommitted): the lowest level, in any case can not be guaranteed.

  More than four isolation levels are Serializable highest level, the lowest Read uncommitted level, of course, the higher the level, the lower the efficiency. Such a level as Serializable, is the way to lock tables (similar to Java multi-thread lock) allows other threads can only wait outside the lock, so usually choose what isolation level should be based on the actual situation. The default in MySQL database isolation level is Repeatable read (repeatable read).

  In the MySQL database, support for the above four isolation levels, the default is Repeatable read (repeatable read); and in the Oracle database, the only support Serializable (serialized) level and Read committed (Read Committed) Both levels , where the default is committed level is Read.

  View the current transaction isolation level in a MySQL database: select @@ tx_isolation;

  Set in a MySQL database transaction isolation levels:   

set [glogal | session] transaction isolation level isolation level name;

 SET TX_ISOLATION = 'name isolation level;'
Example 1: View the current transaction isolation level:

  

Example 2: The isolation level is set to Read uncommitted transaction level:

  

or:

  

Remember: the isolation level of the database must be a prior transaction in the open!

  If you are using JDBC for database transaction isolation level is set, it should also be calling the Connection object before setAutoCommit (false) method. Call the Connection object setTransactionIsolation (level) to set the current link isolation level, as the parameter level, you can use the field Connection object:

  

JDBC isolation level set in the part of the code:

  

  Postscript: isolation level setting is only valid for the current link. For using the MySQL command window, a window is equivalent to a link, the current window to set the isolation level is only valid for the current window of affairs; for JDBC for database operations, a Connection object is equivalent to a link, and for the Connection object set the isolation level only valid Connection object, independent of other links Connection object.

 

 

 

Guess you like

Origin www.cnblogs.com/HUIWANG/p/11019224.html