Query F
Examples F. () Can be referenced in the query field, the value to compare different fields of the same model example two
from django.db.models import F,Q # Inquiry number is greater than the number of stock sold goods res = models.Product.objects.filter(maichu__gt=F("kucun"))
Django supports between F. () And the object F. () Between the object and the addition, subtraction modulo operation constant and
# The prices of all commodities increased by 100 models.Product.objects.update(price=F("price")+100)
To modify char field, 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
# The names of all the goods after the suffix from django.db.models.functions import Concat from django.db.models import Value models.Product.objects.update (name = Concat (F ( "name"), Value ( "Cleavage"))) # can not be used as string concatenation + d, it must be built using methods concat
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
# Query sales price is lower than 100 and more than 100 commodities
from django.db.models import Q models.Product.objects.filter(Q(maichu__gt=100)|Q(price__lt=100))
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
# Query inventory number is 100 and the number of products sold is not zero models.Product.objects.filter(Q(kucun=100)&~Q(maichu=0))
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
# Query inventory number is 100 and the number of products sold is not zero models.Product.objects.filter(Q(kucun__gt=60), name__contains="新款")
When the condition of the query string for the front end came, we can query the object with Q
from django.db.models import F,Q q = Q () # Q instantiate an object q.children.append (( "price", 188.88)) # Add as a tuple q.connector = "or" # Q objects will become the default and relations or relations q.children.append (( "name", "high-heeled shoes explosion models")) res = models.Product.objects, filter (q) # pass filter directly to the query object print(res)
Affairs
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
from django.db.models import F from django.db import transaction # Open transaction try: with transaction.atomic(): # Create an order data models.Order.objects.create(num="110110111", product_id=1, count=1) # Can be executed successfully models.Product.objects.filter(id=1).update(kucun=F("kucun")-1, maichu=F("maichu")+1) except Exception as e: print (e)
Detailed methods Queryset
- The difference update () and save () of
Both are changes to the data save operation, but save () function is a data column all the data items of all the re-write it again, and update () is updated for the high efficiency of the modified item for less time-consuming
-
bulk_create bulk insert data
l = []
for i in range(100): # The generated data object to a list l.append(models.Book.objects(title="第%s本书"%i))
models.Book.objects.bulk_create(l)
Other methods queryset
################################################################## # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET # ################################################################## def all(self) # Get all the data objects def filter(self, *args, **kwargs) # Condition query # Condition can be: parameters, dictionary, Q def exclude(self, *args, **kwargs) # Condition query # Condition can be: parameters, dictionary, Q def select_related(self, *fields) Related properties: even for table join operation between tables, acquiring data associated with the disposable. to sum up: 1 . Select_related and many-to-one relationship between the main needle optimization. 2 . Select_related use of SQL JOIN statement optimization, be optimized by reducing the number of SQL queries and improve performance. def prefetch_related(self, *lookups) Performance-related: even when multi-table table operations will be slower, use its SQL query is executed multiple times to achieve even operating table in the Python code. to sum up: 1 . For many to many fields (ManyToManyField) and many fields, you may be used prefetch_related () to optimize. 2 . Prefetch_related () method is separately optimized query each table, and then deal with their relationship with Python. def annotate(self, *args, **kwargs) # Used to implement the aggregation group by query from django.db.models import Count, Avg, Max, Min, Sum v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id')) # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id')).filter(uid__gt=1) # SELECT u_id, COUNT(ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1 v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id',distinct=True)).filter(uid__gt=1) # SELECT u_id, COUNT( DISTINCT ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1 def distinct(self, *field_names) # A distinct deduplication models.UserInfo.objects.values('nid').distinct() # select distinct nid from userinfo Note: Use only heavy to be distinct in PostgreSQL def order_by(self, *field_names) # For sorting models.UserInfo.objects.all().order_by('-id','age') def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None) # Construct additional criteria or maps, such as: a subquery Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,)) Entry.objects.extra(where=['headline=%s'], params=['Lennon']) Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"]) Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid']) def reverse(self): # Reverse models.UserInfo.objects.all().order_by('-nid').reverse() # Note: If there is order_by, reverse the reverse order, if multiple sort the eleven reverse def defer(self, *fields): models.UserInfo.objects.defer('username','id') or models.UserInfo.objects.filter(...).defer('username','id') # Exclude a column mapping data def only(self, *fields): # Fetch only the data in a table models.UserInfo.objects.only('username','id') or models.UserInfo.objects.filter(...).only('username','id') def using(self, alias): Specify database alias parameters (set in the setting) ################################################## # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS # ################################################## def raw(self, raw_query, params=None, translations=None, using=None): # Execute native SQL models.UserInfo.objects.raw('select * from userinfo') # If other SQL tables must be set to the current name of the primary key column names UserInfo object models.UserInfo.objects.raw('select id as nid from 其他表') # Set the parameters for the native SQL models.UserInfo.objects.raw('select id as nid from userinfo where nid>%s', params=[12,]) # Will get to the column names to specify column names name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'} Person.objects.raw('SELECT * FROM some_other_table', translations=name_map) # Specify the database models.UserInfo.objects.raw('select * from userinfo', using="default") Native SQL ################### ################### from django.db import connection, connections cursor = connection.cursor() # cursor = connections['default'].cursor() cursor.execute("""SELECT * from auth_user where id = %s""", [1]) row = cursor.fetchone() # fetchall()/fetchmany(..) def values(self, *fields): # Obtain per-line data dictionary format def values_list(self, *fields, **kwargs): # Per-line data acquisition Ganso def dates(self, field_name, kind, order='ASC'): # Be a part based on the time to re-locate and intercept specified content # Kind can only be: "year" (years), "month" (year - month), "day" (year - month - day) # Order only: "ASC" "DESC" # And get the converted time - year: -01-01 years - month: Year - Month -01 - day: year - month - day models.DatePlus.objects.dates('ctime','day','DESC') def datetimes(self, field_name, kind, order='ASC', tzinfo=None): # For a part based on the time taken to re-find and specify the content, the conversion time is the time zone specified # kind只能是 "year", "month", "day", "hour", "minute", "second" # order只能是:"ASC" "DESC" # Tzinfo time zone objects models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.UTC) models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.timezone('Asia/Shanghai')) """ pip3 install pytz import pytz pytz.all_timezones pytz.timezone(‘Asia/Shanghai’) """ def none(self): Empty QuerySet object # #################################### # METHODS THAT DO DATABASE QUERIES # #################################### def aggregate(self, *args, **kwargs): # Aggregate functions, acquires dictionary type polymerization results from django.db.models import Count, Avg, Max, Min, Sum result = models.UserInfo.objects.aggregate(k=Count('u_id', distinct=True), n=Count('nid')) ===> {'k': 3, 'n': 4} def count(self): # Gets the count def get(self, *args, **kwargs): # Obtain a single object def create(self, **kwargs): # Create Object def bulk_create(self, objs, batch_size=None): # Bulk Insert # Batch_size represent the number once inserted objs = [ models.DDD(name='r11'), models.DDD(name='r22') ] models.DDD.objects.bulk_create(objs, 10) def get_or_create(self, defaults=None, **kwargs): # If so, get, otherwise, create # Defaults specified when created, the value of other fields obj, created = models.UserInfo.objects.get_or_create(username='root1', defaults={'email': '1111111','u_id': 2, 't_id': 2}) def update_or_create(self, defaults=None, **kwargs): # If so, update, or create Other fields # defaults specified when you create or update the obj, created = models.UserInfo.objects.update_or_create(username='root1', defaults={'email': '1111111','u_id': 2, 't_id': 1}) def first(self): # Get the first def last(self): # Get the last one def in_bulk(self, id_list=None): # Finds based on the primary key ID id_list = [11,21,31] models.DDD.objects.in_bulk(id_list) def delete(self): # Delete def update(self, **kwargs): # Update def exists(self): # Are there results