Hướng dẫn python if query is none - python nếu truy vấn không có

Tôi đã có một vấn đề tương tự khi tôi cần thực hiện nhiều truy vấn SQL. Vấn đề là một số truy vấn đã không trả về kết quả và tôi muốn in kết quả đó. Và đã có một sai lầm. Như đã viết, có một số giải pháp.

Show
if cursor.description is None:
    # No recordset for INSERT, UPDATE, CREATE, etc
    pass
else:
    # Recordset for SELECT

Cũng như:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists

Một trong những giải pháp là:

Khối

# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)
1 và
# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)
2 cho phép bạn xử lý ________ 53/________ 54. Khối
# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)
5 cho phép bạn thực thi mã, bất kể kết quả của các khối
# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)
1 và
# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)
2. Vì vậy, vấn đề được trình bày có thể được giải quyết bằng cách sử dụng nó.

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))

output:

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************

Ví dụ ở trên chỉ trình bày sử dụng đơn giản như một ý tưởng có thể giúp giải pháp của bạn. Tất nhiên, bạn cũng nên chú ý đến các lỗi khác, chẳng hạn như tính chính xác của truy vấn, v.v.

10.5.8 & nbsp; mysqlcursor.fetchone () Phương thức

Cú pháp:

row = cursor.fetchone()

Phương thức này lấy hàng tiếp theo của bộ kết quả truy vấn và trả về một chuỗi duy nhất hoặc

# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)
8 nếu không có thêm hàng. Theo mặc định, bộ tuple được trả về bao gồm dữ liệu được trả về bởi máy chủ MySQL, được chuyển đổi thành các đối tượng Python. Nếu con trỏ là một con trỏ thô, không có sự chuyển đổi như vậy xảy ra; Xem Phần & NBSP; 10.6.2, Lớp con trỏ.MysqlCursorraw.

Phương thức

# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)
9 được sử dụng bởi fetchall () và fetchmany (). Nó cũng được sử dụng khi một con trỏ được sử dụng như một người lặp.

Ví dụ sau đây cho thấy hai cách tương đương để xử lý kết quả truy vấn. Lần đầu tiên sử dụng

# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)
9 trong vòng lặp
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
1, thứ hai sử dụng con trỏ làm người lặp:

# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)

Bạn phải tìm nạp tất cả các hàng cho truy vấn hiện tại trước khi thực hiện các câu lệnh mới bằng cách sử dụng cùng một kết nối.


Các biểu thức truy vấn mô tả một giá trị hoặc tính toán có thể được sử dụng như một phần của bản cập nhật, tạo, lọc, thứ tự theo, chú thích hoặc tổng hợp. Khi một biểu thức xuất ra giá trị boolean, nó có thể được sử dụng trực tiếp trong các bộ lọc. Có một số biểu thức tích hợp (được ghi lại bên dưới) có thể được sử dụng để giúp bạn viết các truy vấn. Biểu thức có thể được kết hợp, hoặc trong một số trường hợp lồng nhau, để tạo thành các tính toán phức tạp hơn.

Số học được hỗ trợ

Django hỗ trợ phủ định, cộng, phép trừ, nhân, chia, số học modulo và toán tử nguồn trên các biểu thức truy vấn, sử dụng hằng số python, biến và thậm chí các biểu thức khác.

Vài ví dụ¶

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)

Biểu thức tích hợp

Ghi chú

Các biểu thức này được định nghĩa trong

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
2 và
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
3, nhưng để thuận tiện, chúng có sẵn và thường được nhập từ
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
4.

from django.db.models import Count, F, Value from django.db.models.functions import Length, Upper from django.db.models.lookups import GreaterThan # Find companies that have more employees than chairs. Company.objects.filter(num_employees__gt=F('num_chairs')) # Find companies that have at least twice as many employees # as chairs. Both the querysets below are equivalent. Company.objects.filter(num_employees__gt=F('num_chairs') * 2) Company.objects.filter( num_employees__gt=F('num_chairs') + F('num_chairs')) # How many chairs are needed for each company to seat all employees? >>> company = Company.objects.filter( ... num_employees__gt=F('num_chairs')).annotate( ... chairs_needed=F('num_employees') - F('num_chairs')).first() >>> company.num_employees 120 >>> company.num_chairs 50 >>> company.chairs_needed 70 # Create a new company using expressions. >>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog'))) # Be sure to refresh it if you need to access the field. >>> company.refresh_from_db() >>> company.ticker 'GOOG' # Annotate models with an aggregated value. Both forms # below are equivalent. Company.objects.annotate(num_products=Count('products')) Company.objects.annotate(num_products=Count(F('products'))) # Aggregates can contain complex computations also Company.objects.annotate(num_offerings=Count(F('products') + F('services'))) # Expressions can also be used in order_by(), either directly Company.objects.order_by(Length('name').asc()) Company.objects.order_by(Length('name').desc()) # or using the double underscore lookup syntax. from django.db.models import CharField from django.db.models.functions import Length CharField.register_lookup(Length) Company.objects.order_by('name__length') # Boolean expression can be used directly in filters. from django.db.models import Exists Company.objects.filter( Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10)) ) # Lookup expressions can also be used directly in filters Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs'))) # or annotations. Company.objects.annotate( need_chairs=GreaterThan(F('num_employees'), F('num_chairs')), ) 5 Biểu thức Jo

Lớp ________ 66¶
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)

Một đối tượng

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 biểu thị giá trị của trường mô hình, giá trị biến đổi của trường mô hình hoặc cột được chú thích. Nó có thể đề cập đến các giá trị trường mô hình và thực hiện các hoạt động cơ sở dữ liệu bằng cách sử dụng chúng mà không thực sự phải kéo chúng ra khỏi cơ sở dữ liệu vào bộ nhớ Python.

Thay vào đó, Django sử dụng đối tượng

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 để tạo biểu thức SQL mô tả hoạt động cần thiết ở cấp cơ sở dữ liệu.

Hãy để thử điều này với một ví dụ. Thông thường, người ta có thể làm điều gì đó như thế này:

# Tintin filed a news story!
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()

Ở đây, chúng tôi đã kéo giá trị của

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
9 từ cơ sở dữ liệu vào bộ nhớ và thao tác nó bằng các toán tử python quen thuộc, sau đó lưu đối tượng trở lại cơ sở dữ liệu. Nhưng thay vào đó chúng ta cũng có thể làm được:

from django.db.models import F

reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed = F('stories_filed') + 1
reporter.save()

Mặc dù

# Tintin filed a news story!
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()
0 trông giống như một gán giá trị Python bình thường cho một thuộc tính thể hiện, nhưng trên thực tế, nó là một cấu trúc SQL mô tả một hoạt động trên cơ sở dữ liệu.

Khi Django gặp một thể hiện

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5, nó sẽ ghi đè các toán tử Python tiêu chuẩn để tạo biểu thức SQL được đóng gói; Trong trường hợp này, một trong đó hướng dẫn cơ sở dữ liệu để tăng trường cơ sở dữ liệu được biểu thị bằng
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
9.

Bất kể giá trị nào là hoặc trên

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
9, Python không bao giờ biết về nó - nó được xử lý hoàn toàn bằng cơ sở dữ liệu. Tất cả các Python, thông qua lớp Django từ ____ ____65, là tạo cú pháp SQL để tham khảo trường và mô tả hoạt động.

Để truy cập giá trị mới được lưu theo cách này, đối tượng phải được tải lại:

reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()

Cũng như được sử dụng trong các hoạt động trên các trường hợp đơn lẻ như trên,

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 có thể được sử dụng trên
# Tintin filed a news story!
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()
6 của các trường hợp đối tượng, với
# Tintin filed a news story!
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()
7. Điều này làm giảm hai truy vấn mà chúng tôi đã sử dụng ở trên -
# Tintin filed a news story!
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()
8 và
# Tintin filed a news story!
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()
9 - chỉ một:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
0

Chúng ta cũng có thể sử dụng

# Tintin filed a news story!
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()
7 để tăng giá trị trường trên nhiều đối tượng - có thể nhanh hơn nhiều so với việc kéo tất cả chúng vào Python từ cơ sở dữ liệu, lặp lại chúng, tăng giá trị trường của từng con và lưu từng cái trở lại cơ sở dữ liệu :

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
1

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 Do đó có thể cung cấp các lợi thế về hiệu suất bằng cách:

  • Nhận cơ sở dữ liệu, thay vì Python, để làm việc
  • Giảm số lượng truy vấn mà một số hoạt động yêu cầu

Tránh các điều kiện chủng tộc bằng cách sử dụng ____ ____ 65¶

Một lợi ích hữu ích khác của

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 là việc có cơ sở dữ liệu - thay vì Python - cập nhật giá trị trường Lĩnh vực tránh được điều kiện cuộc đua.

Nếu hai luồng Python thực thi mã trong ví dụ đầu tiên ở trên, một luồng có thể truy xuất, tăng và lưu giá trị trường sau khi tên kia đã lấy nó từ cơ sở dữ liệu. Giá trị mà luồng thứ hai tiết kiệm sẽ dựa trên giá trị ban đầu; Công việc của chủ đề đầu tiên sẽ bị mất.

Nếu cơ sở dữ liệu chịu trách nhiệm cập nhật trường, quá trình này mạnh hơn: nó sẽ chỉ cập nhật trường dựa trên giá trị của trường trong cơ sở dữ liệu khi

# Tintin filed a news story!
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()
9 hoặc
# Tintin filed a news story!
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()
7 được thực thi, thay vì dựa trên giá trị của nó khi ví dụ đã được lấy.

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 Bài tập vẫn tồn tại sau ________ 87¶

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 Các đối tượng được gán cho các trường mô hình vẫn tồn tại sau khi lưu thể hiện mô hình và sẽ được áp dụng trên mỗi
# Tintin filed a news story!
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()
9. Ví dụ:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
2

reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()
0 sẽ được cập nhật hai lần trong trường hợp này. Nếu nó ban đầu
reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()
1, giá trị cuối cùng sẽ là
reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()
2. Sự kiên trì này có thể tránh được bằng cách tải lại đối tượng mô hình sau khi lưu nó, ví dụ, bằng cách sử dụng
reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()
3.

Sử dụng
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 trong Bộ lọc lor

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 cũng rất hữu ích trong các bộ lọc
reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()
6, trong đó chúng có thể lọc một tập hợp các đối tượng theo tiêu chí dựa trên các giá trị trường của chúng, thay vì trên các giá trị Python.

Điều này được ghi lại trong việc sử dụng các biểu thức f () trong các truy vấn.using F() expressions in queries.

Sử dụng
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 với chú thích Bur

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 có thể được sử dụng để tạo các trường động trên các mô hình của bạn bằng cách kết hợp các trường khác nhau với số học:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
3

Nếu các trường mà bạn kết hợp là các loại khác nhau, bạn sẽ cần nói Django loại trường nào sẽ được trả về. Vì

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 không hỗ trợ trực tiếp
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
00, bạn sẽ cần phải bọc biểu thức bằng
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
01:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
4

Khi tham chiếu các trường quan hệ như

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
02,
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 trả về giá trị khóa chính thay vì một thể hiện mô hình:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
5

Sử dụng
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 để sắp xếp các giá trị null

Sử dụng

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 và đối số từ khóa
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
06 hoặc
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
07 thành
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
08 hoặc
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
09 để kiểm soát thứ tự của một trường giá trị null. Theo mặc định, việc đặt hàng phụ thuộc vào cơ sở dữ liệu của bạn.

Ví dụ, để sắp xếp các công ty mà thiên đường đã được liên lạc (

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
10 là NULL) sau khi các công ty đã được liên hệ:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
6

exist = cursor.fetchone() if exist is None: ... # does not exist else: ... # exists 11 biểu thức

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
11 Biểu thức là loại cơ sở của tất cả các biểu thức liên quan đến các chức năng cơ sở dữ liệu như
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
13 và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
14 hoặc các tập hợp như
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
15. Chúng có thể được sử dụng trực tiếp:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
7

Hoặc chúng có thể được sử dụng để xây dựng một thư viện các chức năng cơ sở dữ liệu:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
8

Nhưng cả hai trường hợp sẽ dẫn đến một truy vấn trong đó mỗi mô hình được chú thích bằng một thuộc tính bổ sung

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
16 được tạo ra, gần như từ SQL sau: sau đây:

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
9

Xem các chức năng cơ sở dữ liệu cho một danh sách các chức năng cơ sở dữ liệu tích hợp.Database Functions for a list of built-in database functions.

API

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
17 như sau:

Lớp ________ 117 (*Biểu thức, ** Thêm) ________ 119¶
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
17(*expressions, **extra
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
19¶

Một thuộc tính lớp mô tả hàm sẽ được tạo. Cụ thể,

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
19 sẽ được nội suy là trình giữ chỗ
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
19 trong
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
22. Mặc định là
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23.

________ 122¶

Một thuộc tính lớp, như một chuỗi định dạng, mô tả SQL được tạo cho hàm này. Mặc định là

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
25.

Nếu bạn đang xây dựng SQL như

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
26 và cần ký tự
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
27 theo nghĩa đen trong truy vấn, tăng gấp bốn lần (
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
28) trong thuộc tính
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
22 vì chuỗi được nội suy hai lần: tham số trong con trỏ cơ sở dữ liệu.

________ 131¶

Một thuộc tính lớp biểu thị ký tự được sử dụng để tham gia danh sách

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
32 cùng nhau. Mặc định là
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
33.

________ 134¶

Một thuộc tính lớp biểu thị số lượng đối số mà hàm chấp nhận. Nếu thuộc tính này được đặt và hàm được gọi với một số biểu thức khác nhau,

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
35 sẽ được nâng lên. Mặc định là
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23.

________ 137 (trình biên dịch, kết nối, hàm = none, memplate = none, arg_joiner = none, ** extr_context) ¶compiler, connection, function=None, template=None, arg_joiner=None, **extra_context

Tạo đoạn SQL cho chức năng cơ sở dữ liệu. Trả về một tuple

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
38, trong đó
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
39 là chuỗi SQL và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
40 là danh sách hoặc tuple của các tham số truy vấn.

Các phương thức

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
41 nên sử dụng
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
19,
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
22,
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
31 và bất kỳ tham số
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
45 nào khác để tùy chỉnh SQL khi cần. Ví dụ:

________ 146¶

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
0

Để tránh lỗ hổng SQL,

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
47 không được chứa đầu vào người dùng không đáng tin cậy vì các giá trị này được nội suy vào chuỗi SQL thay vì được truyền dưới dạng tham số truy vấn, trong đó trình điều khiển cơ sở dữ liệu sẽ thoát khỏi chúng.must not contain untrusted user input as these values are interpolated into the SQL string rather than passed as query parameters, where the database driver would escape them.

Đối số

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
48 là danh sách các biểu thức vị trí mà hàm sẽ được áp dụng. Các biểu thức sẽ được chuyển đổi thành các chuỗi, được nối với nhau với
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
31, và sau đó được nội suy vào
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
22 dưới dạng trình giữ chỗ
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
32.

Đối số vị trí có thể là các biểu thức hoặc giá trị python. Các chuỗi được coi là tham chiếu cột và sẽ được bọc trong các biểu thức

from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 trong khi các giá trị khác sẽ được bọc trong các biểu thức
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
53.

Các kwarg

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
54 là các cặp
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
55 có thể được nội suy vào thuộc tính
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
22. Để tránh lỗ hổng SQL,
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
57 không được chứa đầu vào người dùng không đáng tin cậy vì các giá trị này được nội suy vào chuỗi SQL thay vì được truyền dưới dạng tham số truy vấn, trong đó trình điều khiển cơ sở dữ liệu sẽ thoát khỏi chúng.must not contain untrusted user input as these values are interpolated into the SQL string rather than passed as query parameters, where the database driver would escape them.

Có thể sử dụng các từ khóa

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
19,
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
22 và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
31 để thay thế các thuộc tính của cùng tên mà không phải xác định lớp của riêng bạn.
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
00 có thể được sử dụng để xác định loại trả về dự kiến.

exist = cursor.fetchone() if exist is None: ... # does not exist else: ... # exists 62 Biểu thức Jo

Một biểu thức tổng hợp là một trường hợp đặc biệt của biểu thức func () thông báo cho truy vấn rằng mệnh đề

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
63 là bắt buộc. Tất cả các hàm tổng hợp, như
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
64 và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
65, kế thừa từ
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
62.Func() expression that informs the query that a
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
63 clause is required. All of the aggregate functions, like
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
64 and
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
65, inherit from
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
62.

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
67 là các biểu thức và biểu thức bọc, bạn có thể biểu diễn một số tính toán phức tạp:

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
1

API

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
67 như sau:

Lớp ________ 167 (*Biểu thức, output_field = none
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
67(*expressions, output_field=None, distinct=False, filter=None, default=None, **extra
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
22¶

Một thuộc tính lớp, như một chuỗi định dạng, mô tả SQL được tạo cho tổng hợp này. Mặc định là

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
71.

________ 119¶

Một thuộc tính lớp mô tả hàm tổng hợp sẽ được tạo. Cụ thể,

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
19 sẽ được nội suy là trình giữ chỗ
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
19 trong
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
22. Mặc định là
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23.

________ 177¶

Mặc định là

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
78 Vì hầu hết các hàm tổng hợp có thể được sử dụng làm biểu thức nguồn trong
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
79.

________ 180¶

Một thuộc tính lớp xác định xem chức năng tổng hợp này có cho phép truyền đối số từ khóa

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
81 hay không. Nếu được đặt thành
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
82 (mặc định),
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
35 sẽ được nâng lên nếu
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
84 được thông qua.

________ 185¶

Mới trong Django 4.0.

Mặc định là

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23 Vì hầu hết các chức năng tổng hợp dẫn đến
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
87 khi được áp dụng cho một tập kết quả trống.

Các đối số vị trí

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
32 có thể bao gồm các biểu thức, biến đổi của trường mô hình hoặc tên của các trường mô hình. Chúng sẽ được chuyển đổi thành một chuỗi và được sử dụng làm trình giữ chỗ
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
32 trong
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
22.

Đối số

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
00 yêu cầu một thể hiện trường mô hình, như
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
92 hoặc
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
93, trong đó Django sẽ tải giá trị sau khi nó được lấy từ cơ sở dữ liệu. Thông thường không cần đối số khi khởi tạo trường mô hình vì bất kỳ đối số nào liên quan đến xác thực dữ liệu (
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
94,
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
95, v.v.) sẽ không được thực thi trên giá trị đầu ra của biểu thức.

Lưu ý rằng

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
00 chỉ được yêu cầu khi Django không thể xác định loại trường nào nên là kết quả. Các biểu thức phức tạp mà các loại trường trộn nên xác định
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
00 mong muốn. Ví dụ: thêm một
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
92 và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
99 cùng nhau có lẽ nên có
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
00 được xác định.

Đối số

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
81 xác định liệu hàm tổng hợp có nên được gọi cho từng giá trị riêng biệt của
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
32 (hoặc tập hợp các giá trị, cho nhiều
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
32). Đối số chỉ được hỗ trợ trên các tập hợp có
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
80 được đặt thành
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
78.

Đối số

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
06 có một
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
07 mà sử dụng để lọc các hàng được tổng hợp. Xem tập hợp có điều kiện và lọc trên các chú thích ví dụ như sử dụng.Conditional aggregation and Filtering on annotations for example usage.

Đối số

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
08 có một giá trị sẽ được chuyển cùng với tổng hợp đến
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
09. Điều này rất hữu ích để chỉ định một giá trị sẽ được trả về ngoài
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23 khi truy vấn (hoặc nhóm) không chứa mục nhập.

Các kwarg

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
54 là các cặp
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
55 có thể được nội suy vào thuộc tính
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
22.

Đã thay đổi trong Django 4.0:

Đối số

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
08 đã được thêm vào.

Tạo các chức năng tổng hợp của riêng bạn

Bạn cũng có thể tạo các chức năng tổng hợp của riêng bạn. Ở mức tối thiểu, bạn cần xác định

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
19, nhưng bạn cũng có thể hoàn toàn tùy chỉnh SQL được tạo ra. Ở đây, một ví dụ ngắn gọn:

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
2

exist = cursor.fetchone() if exist is None: ... # does not exist else: ... # exists 53 Biểu thức Jo

Lớp ________ 217 (giá trị, output_field = none) ¶
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
17(value, output_field=None

Một đối tượng

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
53 biểu thị thành phần nhỏ nhất có thể của biểu thức: một giá trị đơn giản. Khi bạn cần biểu diễn giá trị của một số nguyên, boolean hoặc chuỗi trong một biểu thức, bạn có thể bọc giá trị đó trong một
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
53.

Bạn sẽ hiếm khi cần sử dụng trực tiếp

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
53. Khi bạn viết biểu thức
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
21, Django ngầm kết thúc
reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()
1 trong
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
53, cho phép sử dụng các giá trị đơn giản trong các biểu thức phức tạp hơn. Bạn sẽ cần sử dụng
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
53 khi bạn muốn chuyển một chuỗi đến một biểu thức. Hầu hết các biểu thức diễn giải một đối số chuỗi là tên của một trường, như
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
25.

Đối số

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
26 mô tả giá trị được bao gồm trong biểu thức, chẳng hạn như
reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()
1,
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
78 hoặc
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23. Django biết cách chuyển đổi các giá trị python này thành loại cơ sở dữ liệu tương ứng của chúng.

Đối số

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
00 phải là một thể hiện trường mô hình, như
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
92 hoặc
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
93, trong đó Django sẽ tải giá trị sau khi nó được lấy từ cơ sở dữ liệu. Thông thường không cần đối số khi khởi tạo trường mô hình vì bất kỳ đối số nào liên quan đến xác thực dữ liệu (
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
94,
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
95, v.v.) sẽ không được thực thi trên giá trị đầu ra của biểu thức. Nếu không có
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
00 được chỉ định, nó sẽ được suy ra từ
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
36 của
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
26 được cung cấp, nếu có thể. Ví dụ: chuyển một thể hiện là
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
38 là
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
26 sẽ mặc định
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
00 đến
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
41.

s = """ set current query acceleration = enable; set current GET_ACCEL_ARCHIVE = yes; SELECT * FROM TABLE_NAME;""" query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))] for sql in query_sqls: print(f"Executing SQL statements ====> {sql} <=====") cursor.execute(sql) print(f"SQL ====> {sql} <===== was executed successfully") try: print("\n****************** RESULT ***********************") for result in cursor.fetchall(): print(result) print("****************** END RESULT ***********************\n") except Exception as e: print(f"SQL: ====> {sql} <==== doesn't have output!\n") # print(str(e)) 42 Biểu thức Jo

Lớp ________ 101 (Biểu thức, Output_Field) ¶
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
01(expression, output_field

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
01 bao quanh một biểu thức khác và cung cấp quyền truy cập vào các thuộc tính, chẳng hạn như
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
00, có thể không có sẵn trên các biểu thức khác.
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
01 là cần thiết khi sử dụng số học trên các biểu thức
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 với các loại khác nhau như được mô tả trong sử dụng f () với các chú thích.Using F() with annotations.

Biểu thức có điều kiện

Biểu thức có điều kiện cho phép bạn sử dụng

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
48
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
49
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
50 logic trong các truy vấn. Django tự nhiên hỗ trợ các biểu thức SQL
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
51. Để biết thêm chi tiết, xem biểu thức có điều kiện.Conditional Expressions.

s = """ set current query acceleration = enable; set current GET_ACCEL_ARCHIVE = yes; SELECT * FROM TABLE_NAME;""" query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))] for sql in query_sqls: print(f"Executing SQL statements ====> {sql} <=====") cursor.execute(sql) print(f"SQL ====> {sql} <===== was executed successfully") try: print("\n****************** RESULT ***********************") for result in cursor.fetchall(): print(result) print("****************** END RESULT ***********************\n") except Exception as e: print(f"SQL: ====> {sql} <==== doesn't have output!\n") # print(str(e)) 52 Biểu thức Jo

Lớp ________ 253 (queryset, output_field = none) ¶
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53(queryset, output_field=None

Bạn có thể thêm một truy vấn con rõ ràng vào

reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()
6 bằng cách sử dụng biểu thức
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53.

Ví dụ: để chú thích mỗi bài đăng với địa chỉ email của tác giả của nhận xét mới nhất về bài đăng đó:

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
3

Trên PostgreSQL, SQL trông giống như:

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
4

Ghi chú

Các ví dụ trong phần này được thiết kế để chỉ ra cách buộc Django thực hiện một truy vấn con. Trong một số trường hợp, có thể viết một truy vấn tương đương thực hiện cùng một nhiệm vụ rõ ràng hơn hoặc hiệu quả hơn.

Tham chiếu các cột từ truy vấn bên ngoài

Lớp ________ 256 (Trường)
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
56(field

Sử dụng

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
56 khi truy vấn trong
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53 cần tham khảo một trường từ truy vấn bên ngoài hoặc biến đổi của nó. Nó hoạt động giống như một biểu thức
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
6 ngoại trừ việc kiểm tra để xem liệu nó có đề cập đến một trường hợp lệ được thực hiện cho đến khi truy vấn bên ngoài được giải quyết không.

Các trường hợp của

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
56 có thể được sử dụng cùng với các trường hợp lồng nhau là
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53 để chỉ một truy vấn chứa không phải là cha mẹ ngay lập tức. Ví dụ, truy vấn này sẽ cần phải nằm trong một cặp phiên bản
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53 lồng nhau để giải quyết chính xác:

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
5

Giới hạn một truy vấn con trong một cột duy nhất

Ví dụ, có những lúc một cột phải được trả về từ

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53 để sử dụng
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53 làm mục tiêu của tra cứu
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
65. Để trả lại tất cả các bình luận cho các bài viết được xuất bản trong ngày cuối cùng:

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
6

Trong trường hợp này, trình điều khiển con phải sử dụng

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
66 để chỉ trả về một cột duy nhất: khóa chính của bài đăng.

Giới hạn trình truy vấn con ở một hàng duy nhất

Để ngăn chặn một truy vấn con trả về nhiều hàng, một lát cắt (

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
67) của queryset được sử dụng:

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
7

Trong trường hợp này, trình điều khiển con chỉ phải trả về một cột duy nhất và một hàng duy nhất: địa chỉ email của nhận xét được tạo gần đây nhất.

.

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
71 Subqueries¶

Lớp ________ 272 (queryset) ¶
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
72(queryset

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
72 là một lớp con
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53 sử dụng câu lệnh SQL
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
75. Trong nhiều trường hợp, nó sẽ hoạt động tốt hơn so với một trình điều khiển con vì cơ sở dữ liệu có thể dừng đánh giá trình điều khiển con khi tìm thấy hàng khớp đầu tiên được tìm thấy.

Ví dụ: để chú thích mỗi bài đăng với việc nó có nhận xét từ trong ngày cuối cùng hay không:

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
8

Trên PostgreSQL, SQL trông giống như:

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
9

Ghi chú

Các ví dụ trong phần này được thiết kế để chỉ ra cách buộc Django thực hiện một truy vấn con. Trong một số trường hợp, có thể viết một truy vấn tương đương thực hiện cùng một nhiệm vụ rõ ràng hơn hoặc hiệu quả hơn.

Tham chiếu các cột từ truy vấn bên ngoài

Lớp ________ 256 (Trường)

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
0

Sử dụng

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
56 khi truy vấn trong
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53 cần tham khảo một trường từ truy vấn bên ngoài hoặc biến đổi của nó. Nó hoạt động giống như một biểu thức
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
6 ngoại trừ việc kiểm tra để xem liệu nó có đề cập đến một trường hợp lệ được thực hiện cho đến khi truy vấn bên ngoài được giải quyết không.

Các trường hợp của
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
56 có thể được sử dụng cùng với các trường hợp lồng nhau là
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53 để chỉ một truy vấn chứa không phải là cha mẹ ngay lập tức. Ví dụ, truy vấn này sẽ cần phải nằm trong một cặp phiên bản
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53 lồng nhau để giải quyết chính xác:

Giới hạn một truy vấn con trong một cột duy nhất

Ví dụ, có những lúc một cột phải được trả về từ

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53 để sử dụng
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
53 làm mục tiêu của tra cứu
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
65. Để trả lại tất cả các bình luận cho các bài viết được xuất bản trong ngày cuối cùng:

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
1

Trong trường hợp này, trình điều khiển con phải sử dụng

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
66 để chỉ trả về một cột duy nhất: khóa chính của bài đăng.

Giới hạn trình truy vấn con ở một hàng duy nhất

Để ngăn chặn một truy vấn con trả về nhiều hàng, một lát cắt (s = """ set current query acceleration = enable; set current GET_ACCEL_ARCHIVE = yes; SELECT * FROM TABLE_NAME;""" query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))] for sql in query_sqls: print(f"Executing SQL statements ====> {sql} <=====") cursor.execute(sql) print(f"SQL ====> {sql} <===== was executed successfully") try: print("\n****************** RESULT ***********************") for result in cursor.fetchall(): print(result) print("****************** END RESULT ***********************\n") except Exception as e: print(f"SQL: ====> {sql} <==== doesn't have output!\n") # print(str(e)) 67) của queryset được sử dụng:

Trong trường hợp này, trình điều khiển con chỉ phải trả về một cột duy nhất và một hàng duy nhất: địa chỉ email của nhận xét được tạo gần đây nhất.
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
04(sql, params, output_field=None

.

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
2

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
71 Subqueries¶

Các biểu thức

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
04 cũng có thể được sử dụng làm mục tiêu của các bộ lọc
s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
65:

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
3

Cảnh báo

Để bảo vệ chống lại các cuộc tấn công tiêm SQL, bạn phải thoát khỏi bất kỳ tham số nào mà người dùng có thể kiểm soát bằng cách sử dụng

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
40.
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
40 là một đối số cần thiết để buộc bạn phải thừa nhận rằng bạn không nội suy SQL của mình với dữ liệu do người dùng cung cấp.

Bạn cũng không được trích dẫn trình giữ chỗ trong chuỗi SQL. Ví dụ này dễ bị tiêm SQL vì các trích dẫn vào khoảng

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
11:

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
4

Bạn có thể đọc thêm về cách bảo vệ tiêm SQL của Django.SQL injection protection works.

Chức năng cửa sổ

Các chức năng cửa sổ cung cấp một cách để áp dụng các chức năng trên các phân vùng. Không giống như hàm tập hợp thông thường tính toán kết quả cuối cùng cho mỗi tập hợp được xác định bởi nhóm theo, các hàm cửa sổ hoạt động trên các khung và phân vùng và tính toán kết quả cho mỗi hàng.frames and partitions, and compute the result for each row.

Bạn có thể chỉ định nhiều cửa sổ trong cùng một truy vấn mà trong Django ORM sẽ tương đương với việc bao gồm nhiều biểu thức trong cuộc gọi truy vấn.annotate (). ORM không sử dụng các cửa sổ được đặt tên, thay vào đó chúng là một phần của các cột đã chọn.QuerySet.annotate() call. The ORM doesn’t make use of named windows, instead they are part of the selected columns.

Lớp ________ 179 (biểu thức, partition_by = none, order_by = none, frame = none, output_field = none) ________ 313¶
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
79(expression, partition_by=None, order_by=None, frame=None, output_field=None
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
13¶

Mặc định là

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
82. Tiêu chuẩn SQL không liên quan đến các chức năng cửa sổ trong Điều khoản
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
05 và Django nêu ra một ngoại lệ khi xây dựng một
reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()
6 sẽ làm điều đó.

________ 122¶

Mặc định là

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
18. Nếu chỉ được cung cấp đối số
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
19, mệnh đề cửa sổ sẽ trống.

Lớp

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
79 là biểu thức chính cho mệnh đề
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
21.

Đối số

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
19 là hàm cửa sổ, hàm tổng hợp hoặc một biểu thức tương thích trong mệnh đề cửa sổ.window function, an aggregate function, or an expression that’s compatible in a window clause.

Đối số

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
23 chấp nhận biểu thức hoặc chuỗi các biểu thức (tên cột phải được bọc trong một đối tượng ____ 66) kiểm soát phân vùng của các hàng. Phân vùng thu hẹp các hàng được sử dụng để tính toán tập kết quả.

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
00 được chỉ định là đối số hoặc bằng biểu thức.

Đối số

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
26 chấp nhận một biểu thức mà bạn có thể gọi
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
27 và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
09, một chuỗi của một tên trường (với tiền tố ____329 tùy chọn cho biết thứ tự giảm dần) hoặc một bộ hoặc danh sách các chuỗi và/hoặc biểu thức. Đặt hàng kiểm soát thứ tự trong đó biểu thức được áp dụng. Ví dụ: nếu bạn tổng hợp các hàng trong một phân vùng, kết quả đầu tiên là giá trị của hàng thứ nhất, thứ hai là tổng của hàng thứ nhất và hàng thứ hai.

Tham số

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
30 chỉ định những hàng khác nên được sử dụng trong tính toán. Xem khung để biết chi tiết.Frames for details.

Đã thay đổi trong Django 4.1:

Hỗ trợ cho

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
26 theo tài liệu tham khảo tên trường đã được thêm vào.

Ví dụ, để chú thích mỗi bộ phim với xếp hạng trung bình cho các bộ phim của cùng một studio trong cùng một thể loại và năm phát hành:

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
5

Điều này cho phép bạn kiểm tra xem một bộ phim được đánh giá tốt hơn hoặc tệ hơn so với các đồng nghiệp của nó.

Bạn có thể muốn áp dụng nhiều biểu thức trên cùng một cửa sổ, tức là, cùng một phân vùng và khung. Ví dụ: bạn có thể sửa đổi ví dụ trước đó cũng bao gồm xếp hạng tốt nhất và tồi tệ nhất trong mỗi nhóm phim (cùng một studio, thể loại và năm phát hành) bằng cách sử dụng ba chức năng cửa sổ trong cùng một truy vấn. Phân vùng và đặt hàng từ ví dụ trước được trích xuất vào từ điển để giảm sự lặp lại:

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
6

Trong số các phụ trợ cơ sở dữ liệu tích hợp của Django, MySQL 8.0.2+, PostgreSQL và Oracle hỗ trợ các biểu thức cửa sổ. Hỗ trợ cho các tính năng biểu thức cửa sổ khác nhau khác nhau giữa các cơ sở dữ liệu khác nhau. Ví dụ: các tùy chọn trong

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
27 và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
09 có thể không được hỗ trợ. Tham khảo tài liệu cho cơ sở dữ liệu của bạn khi cần thiết.

Khung

Đối với khung cửa sổ, bạn có thể chọn chuỗi hàng dựa trên phạm vi hoặc chuỗi hàng thông thường.

Lớp ________ 334 (start = none, end = none) ________ 335¶
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
34(start=None, end=None
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
35¶

Thuộc tính này được đặt thành

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
36.

PostgreSQL có hỗ trợ hạn chế cho

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
34 và chỉ hỗ trợ việc sử dụng các điểm bắt đầu và cuối tiêu chuẩn, chẳng hạn như
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
38 và
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
39.

Lớp ________ 340 (start = none, end = none) ________ 335¶
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
40(start=None, end=None
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
35¶

Thuộc tính này được đặt thành

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
42.

Cả hai lớp trả về SQL với mẫu:

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
7

Khung thu hẹp các hàng được sử dụng để tính toán kết quả. Họ chuyển từ một số điểm bắt đầu sang một số điểm cuối được chỉ định. Các khung có thể được sử dụng có và không có phân vùng, nhưng nó thường là một ý tưởng tốt để chỉ định một đơn đặt hàng của cửa sổ để đảm bảo kết quả xác định. Trong một khung, một ngang hàng trong khung là một hàng có giá trị tương đương hoặc tất cả các hàng nếu một mệnh đề đặt hàng không có mặt.

Điểm bắt đầu mặc định cho một khung là

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
43 là hàng đầu tiên của phân vùng. Điểm cuối luôn được bao gồm rõ ràng trong SQL được tạo bởi ORM và theo mặc định
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
44. Khung mặc định bao gồm tất cả các hàng từ phân vùng đến hàng cuối cùng trong tập hợp.

Các giá trị được chấp nhận cho các đối số

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
45 và
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
46 là
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23, số nguyên hoặc không. Một số nguyên âm cho
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
45 dẫn đến
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
49, trong khi
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23 mang lại
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
43. Đối với cả
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
45 và
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
46, số 0 sẽ trả lại
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
38. Số nguyên dương được chấp nhận cho
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
46.

Có một sự khác biệt trong những gì

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
38 bao gồm. Khi được chỉ định ở chế độ
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
57, khung bắt đầu hoặc kết thúc bằng hàng hiện tại. Khi được chỉ định ở chế độ
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
58, khung bắt đầu hoặc kết thúc ở mức đầu tiên hoặc cuối cùng theo mệnh đề đặt hàng. Do đó,
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
59 đánh giá biểu thức cho các hàng có cùng giá trị được chỉ định bởi thứ tự. Bởi vì mẫu bao gồm cả điểm
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
45 và
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
46, điều này có thể được thể hiện bằng:

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
8

Nếu một bộ phim của bạn, các bộ phim đã được mô tả là các bộ phim được phát hành bởi cùng một studio trong cùng một thể loại trong cùng một năm, ví dụ

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
40 này sẽ chú thích cho mỗi bộ phim với xếp hạng trung bình của một bộ phim trước hai và hai đồng nghiệp sau:

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
9

Nếu cơ sở dữ liệu hỗ trợ nó, bạn có thể chỉ định điểm bắt đầu và điểm cuối dựa trên các giá trị của một biểu thức trong phân vùng. Nếu trường

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
63 của mô hình
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
64 lưu trữ tháng phát hành của mỗi bộ phim, ví dụ
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
34 này sẽ chú thích cho mỗi bộ phim với xếp hạng trung bình của một bộ phim đồng nghiệp được phát hành từ mười hai tháng trước và mười hai tháng sau mỗi bộ phim:

row = cursor.fetchone()
0

Thông tin kĩ thuật¶

Dưới đây bạn sẽ tìm thấy các chi tiết triển khai kỹ thuật có thể hữu ích cho các tác giả thư viện. API kỹ thuật và các ví dụ dưới đây sẽ giúp tạo các biểu thức truy vấn chung có thể mở rộng chức năng tích hợp mà Django cung cấp.

API biểu thức

Các biểu thức truy vấn thực hiện API biểu thức truy vấn, nhưng cũng hiển thị một số phương thức và thuộc tính bổ sung được liệt kê dưới đây. Tất cả các biểu thức truy vấn phải thừa hưởng từ

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
66 hoặc một lớp con có liên quan.query expression API, but also expose a number of extra methods and attributes listed below. All query expressions must inherit from
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
66 or a relevant subclass.

Khi một biểu thức truy vấn kết thúc một biểu thức khác, nó chịu trách nhiệm gọi các phương thức thích hợp trên biểu thức được bọc.

Lớp ________ 367¶ ________ 368¶
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
67¶
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
68¶

Nói với Django rằng biểu thức này chứa một tổng hợp và một điều khoản

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
63 cần được thêm vào truy vấn.

________ 370¶

Nói với Django rằng biểu thức này chứa biểu thức

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
79. Ví dụ, nó đã sử dụng để không cho phép các biểu thức chức năng cửa sổ trong các truy vấn sửa đổi dữ liệu.

________ 313¶

Nói với Django rằng biểu thức này có thể được tham chiếu trong

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
73. Mặc định là
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
78.

________ 177¶

Nói với Django rằng biểu thức này có thể được sử dụng làm biểu thức nguồn trong

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
79. Mặc định là
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
82.

________ 185¶

Mới trong Django 4.0.

Nói với Django giá trị nào sẽ được trả về khi biểu thức được sử dụng để áp dụng hàm trên tập kết quả trống. Mặc định là

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
79 buộc biểu thức sẽ được tính toán trên cơ sở dữ liệu.

________ 380 (truy vấn = không, allow_joins = true, tái sử dụng = khôngquery=None, allow_joins=True, reuse=None, summarize=False, for_save=False

Cung cấp cơ hội để thực hiện bất kỳ tiền xử lý hoặc xác nhận biểu thức trước khi nó thêm vào truy vấn.

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
81 cũng phải được gọi trên bất kỳ biểu thức lồng nhau nào. A
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
82 của
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
83 nên được trả lại với bất kỳ phép biến đổi cần thiết nào.

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
84 là triển khai truy vấn phụ trợ.

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
85 là một boolean cho phép hoặc từ chối việc sử dụng các phép nối trong truy vấn.

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
86 là một tập hợp các kết hợp có thể tái sử dụng cho các kịch bản đa tham gia.

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
87 là một boolean, khi
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
78, báo hiệu rằng truy vấn được tính toán là một truy vấn tổng hợp đầu cuối.

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
89 là một boolean, khi
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
78, báo hiệu rằng truy vấn được thực thi đang thực hiện tạo hoặc cập nhật.

________ 391 ()

Trả về một danh sách đặt hàng của các biểu thức bên trong. Ví dụ:

row = cursor.fetchone()
1

________ 392 (biểu thức) ¶expressions

Lấy một danh sách các biểu thức và lưu trữ chúng sao cho

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
93 có thể trả lại chúng.

________ 394 (Change_map) ¶change_map

Trả về một bản sao (bản sao) của

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
83, với bất kỳ bí danh cột nào được dán nhãn lại. Các bí danh cột được đổi tên khi các nhóm con được tạo.
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
96 cũng nên được gọi trên bất kỳ biểu thức lồng nhau nào và được gán cho bản sao.

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
97 là một bản đồ từ điển lập bản đồ bí danh cũ cho các bí danh mới.

Example:

row = cursor.fetchone()
2

________ 398 (giá trị, biểu thức, kết nối) ¶value, expression, connection

Một móc cho phép biểu thức ép buộc

s = """ set current query acceleration = enable;
        set current GET_ACCEL_ARCHIVE = yes;
        SELECT * FROM TABLE_NAME;"""

query_sqls = [i.strip() + ";" for i in filter(None, s.split(';'))]
for sql in query_sqls:
    print(f"Executing SQL statements ====> {sql} <=====")
    cursor.execute(sql)
    print(f"SQL ====> {sql} <===== was executed successfully")
    try:
        print("\n****************** RESULT ***********************")
        for result in cursor.fetchall():
            print(result)
        print("****************** END RESULT ***********************\n")
    except Exception as e:
        print(f"SQL: ====> {sql} <==== doesn't have output!\n")
        # print(str(e))
26 thành một loại thích hợp hơn.

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
19 giống như
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
83.

________ 402 (bí danh = không) ¶alias=None

Chịu trách nhiệm trả về danh sách các tài liệu tham khảo cột bằng biểu thức này.

row = cursor.fetchone()
03 nên được gọi trên bất kỳ biểu thức lồng nhau nào.
from django.db.models import Count, F, Value
from django.db.models.functions import Length, Upper
from django.db.models.lookups import GreaterThan

# Find companies that have more employees than chairs.
Company.objects.filter(num_employees__gt=F('num_chairs'))

# Find companies that have at least twice as many employees
# as chairs. Both the querysets below are equivalent.
Company.objects.filter(num_employees__gt=F('num_chairs') * 2)
Company.objects.filter(
    num_employees__gt=F('num_chairs') + F('num_chairs'))

# How many chairs are needed for each company to seat all employees?
>>> company = Company.objects.filter(
...    num_employees__gt=F('num_chairs')).annotate(
...    chairs_needed=F('num_employees') - F('num_chairs')).first()
>>> company.num_employees
120
>>> company.num_chairs
50
>>> company.chairs_needed
70

# Create a new company using expressions.
>>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))
# Be sure to refresh it if you need to access the field.
>>> company.refresh_from_db()
>>> company.ticker
'GOOG'

# Annotate models with an aggregated value. Both forms
# below are equivalent.
Company.objects.annotate(num_products=Count('products'))
Company.objects.annotate(num_products=Count(F('products')))

# Aggregates can contain complex computations also
Company.objects.annotate(num_offerings=Count(F('products') + F('services')))

# Expressions can also be used in order_by(), either directly
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())
# or using the double underscore lookup syntax.
from django.db.models import CharField
from django.db.models.functions import Length
CharField.register_lookup(Length)
Company.objects.order_by('name__length')

# Boolean expression can be used directly in filters.
from django.db.models import Exists
Company.objects.filter(
    Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))
)

# Lookup expressions can also be used directly in filters
Company.objects.filter(GreaterThan(F('num_employees'), F('num_chairs')))
# or annotations.
Company.objects.annotate(
    need_chairs=GreaterThan(F('num_employees'), F('num_chairs')),
)
5 Các đối tượng, đặc biệt, giữ một tham chiếu đến một cột. Tham số
row = cursor.fetchone()
05 sẽ là
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23 trừ khi biểu thức đã được chú thích và được sử dụng để nhóm.

________ 407 (nulls_first = none, nulls_last = none) ¶nulls_first=None, nulls_last=None

Trả về biểu thức sẵn sàng để được sắp xếp theo thứ tự tăng dần.

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
06 và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
07 Xác định cách sắp xếp các giá trị null. Xem sử dụng f () để sắp xếp các giá trị null ví dụ như sử dụng.Using F() to sort null values for example usage.

Đã thay đổi trong Django 4.1:

Trong các phiên bản cũ hơn,

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
06 và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
07 được mặc định là
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
82.

Đã không dùng nữa kể từ phiên bản 4.1: Truyền

row = cursor.fetchone()
13 hoặc
row = cursor.fetchone()
14 đến
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
27 không được chấp nhận. Sử dụng
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23 thay thế.Passing
row = cursor.fetchone()
13 or
row = cursor.fetchone()
14 to
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
27 is deprecated. Use
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23 instead.

________ 417 (nulls_first = none, nulls_last = none) ¶nulls_first=None, nulls_last=None

Trả về biểu thức sẵn sàng để được sắp xếp theo thứ tự giảm dần.

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
06 và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
07 Xác định cách sắp xếp các giá trị null. Xem sử dụng f () để sắp xếp các giá trị null ví dụ như sử dụng.Using F() to sort null values for example usage.

Đã thay đổi trong Django 4.1:

Trong các phiên bản cũ hơn,

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
06 và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
07 được mặc định là
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
82.

Đã không dùng nữa kể từ phiên bản 4.1: Truyền

row = cursor.fetchone()
13 hoặc
row = cursor.fetchone()
14 đến
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
27 không được chấp nhận. Sử dụng
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23 thay thế.Passing
row = cursor.fetchone()
13 or
row = cursor.fetchone()
14 to
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
09 is deprecated. Use
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
23 instead.

________ 417 (nulls_first = none, nulls_last = none) ¶

Trả về biểu thức sẵn sàng để được sắp xếp theo thứ tự giảm dần.

Đã không dùng nữa kể từ phiên bản 4.1: Truyền row = cursor.fetchone()13 hoặc row = cursor.fetchone()14 đến exist = cursor.fetchone() if exist is None: ... # does not exist else: ... # exists 09 không được chấp nhận. Sử dụng exist = cursor.fetchone() if exist is None: ... # does not exist else: ... # exists 23 thay thế.

________ 427 ()Func() expressions.

Trả về

Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
83 với bất kỳ sửa đổi nào cần thiết để đảo ngược thứ tự sắp xếp trong cuộc gọi
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
26. Ví dụ, một biểu thức thực hiện
row = cursor.fetchone()
30 sẽ thay đổi giá trị của nó là
row = cursor.fetchone()
31. Việc sửa đổi chỉ được yêu cầu cho các biểu thức thực hiện thứ tự sắp xếp như
row = cursor.fetchone()
32. Phương pháp này được gọi là khi
row = cursor.fetchone()
33 được gọi trên một truy vấn.

Viết các biểu thức truy vấn của riêng bạn

row = cursor.fetchone()
3

Bạn có thể viết các lớp biểu thức truy vấn của riêng mình sử dụng và có thể tích hợp với các biểu thức truy vấn khác. Hãy cùng bước qua một ví dụ bằng cách viết một triển khai hàm

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
13 SQL, mà không cần sử dụng các biểu thức func () tích hợp.

Hàm

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
13 SQL được định nghĩa là lấy danh sách các cột hoặc giá trị. Nó sẽ trả về cột hoặc giá trị đầu tiên mà
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
87.

row = cursor.fetchone()
4

Chúng tôi sẽ bắt đầu bằng cách xác định mẫu sẽ được sử dụng cho SQL Generation và phương thức

row = cursor.fetchone()
37 để đặt một số thuộc tính:

row = cursor.fetchone()
5

Chúng tôi thực hiện một số xác thực cơ bản trên các tham số, bao gồm yêu cầu ít nhất 2 cột hoặc giá trị và đảm bảo chúng là biểu thức. Chúng tôi đang yêu cầu

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
00 ở đây để Django biết loại trường mô hình nào để gán kết quả cuối cùng.

Bây giờ chúng tôi thực hiện tiền xử lý và xác nhận. Vì chúng tôi không có bất kỳ xác nhận nào của chúng tôi vào thời điểm này, chúng tôi ủy thác cho các biểu thức lồng nhau:

Tiếp theo, chúng tôi viết phương thức chịu trách nhiệm tạo SQL:

Các phương thức

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
30 có thể hỗ trợ các đối số từ khóa tùy chỉnh, cho phép các phương thức
row = cursor.fetchone()
40 ghi đè dữ liệu được sử dụng để tạo chuỗi SQL. Sử dụng các đối số từ khóa
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
30 để tùy biến thích hợp hơn để đột biến
Executing SQL statements ====> set current query acceleration = enable; <=====
SQL: ====> set current query acceleration = enable; <==== doesn't have output!

Executing SQL statements ====> set current GET_ACCEL_ARCHIVE = yes; <=====
SQL: ====> set current GET_ACCEL_ARCHIVE = yes; <==== doesn't have output!

Executing SQL statements ====> SELECT * FROM TABLE_NAME; <=====

****************** RESULT ***********************

       ----------   DATA   ----------

****************** END RESULT ***********************
83 trong các phương thức
row = cursor.fetchone()
40 vì phương pháp sau có thể dẫn đến lỗi khi chạy trên các phụ trợ cơ sở dữ liệu khác nhau. Nếu lớp của bạn dựa vào các thuộc tính lớp để xác định dữ liệu, hãy xem xét cho phép ghi đè trong phương thức
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
30 của bạn.

row = cursor.fetchone()
6

Chúng tôi tạo SQL cho mỗi

exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
32 bằng cách sử dụng phương pháp
row = cursor.fetchone()
46 và tham gia kết quả cùng với dấu phẩy. Sau đó, mẫu được điền vào dữ liệu của chúng tôi và SQL và các tham số được trả về.

row = cursor.fetchone()
7

Chúng tôi cũng đã xác định một triển khai tùy chỉnh dành riêng cho phụ trợ Oracle. Hàm
row = cursor.fetchone()
47 sẽ được gọi thay vì
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
30 nếu phần phụ trợ của Oracle được sử dụng.

Cuối cùng, chúng tôi thực hiện phần còn lại của các phương thức cho phép biểu thức truy vấn của chúng tôi phát tốt với các biểu thức truy vấn khác:

Hãy để xem cách thức hoạt động của nó:

row = cursor.fetchone()
8

Tránh SQL Injection¶

Vì các đối số từ khóa ________ 117, cho

row = cursor.fetchone()
37 (
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
54) và
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
30 (
exist = cursor.fetchone()
if exist is None:
  ... # does not exist
else:
  ... # exists
45) được nội suy vào chuỗi SQL thay vì được truyền dưới dạng tham số truy vấn (trong đó trình điều khiển cơ sở dữ liệu sẽ thoát khỏi chúng), chúng không được chứa đầu vào người dùng không đáng yêu.

row = cursor.fetchone()
9

Ví dụ: nếu

row = cursor.fetchone()
54 được cung cấp, chức năng này dễ bị tiêm SQL: SQL:

Hàm này tạo ra một chuỗi SQL mà không có bất kỳ tham số nào. Do row = cursor.fetchone()54 được chuyển đến row = cursor.fetchone()56 dưới dạng đối số từ khóa, nên nó đã nội suy vào chuỗi SQL trước khi truy vấn được gửi đến cơ sở dữ liệu.

Ở đây, một bản viết lại đã sửa chữa:

Thay vào đó, với

row = cursor.fetchone()
54 được thông qua như một đối số vị trí, nó sẽ được truyền dưới dạng tham số trong truy vấn cơ sở dữ liệu.

# Using a while loop
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
while row is not None:
  print(row)
  row = cursor.fetchone()

# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)
0

Thêm hỗ trợ vào cơ sở dữ liệu của bên thứ ba phụ trợ

Chúng tôi sử dụng

row = cursor.fetchone()
61 vì
row = cursor.fetchone()
66 trả về
row = cursor.fetchone()
67 cho phần phụ trợ.

Các phụ trợ của bên thứ ba có thể đăng ký các chức năng của chúng trong tệp cấp cao nhất

row = cursor.fetchone()
68 của gói phụ trợ hoặc trong tệp cấp cao nhất
row = cursor.fetchone()
69 (hoặc gói) được nhập từ cấp cao nhất
row = cursor.fetchone()
68.

Đối với các dự án người dùng muốn vá lỗi phụ trợ mà họ sử dụng, mã này sẽ sống theo phương thức

row = cursor.fetchone()
71.

Làm thế nào để bạn kiểm tra xem một bản ghi có trống trong Python không?

Sử dụng Len () với toán tử so sánh trong mã ở trên, Len (py_list) == 0 sẽ đúng nếu danh sách trống và sẽ được chuyển hướng đến khối khác. In the code above, len(py_list) == 0 will be true if the list is empty and will will be redirected to the else block.

Làm thế nào để bạn kiểm tra xem một kết quả có trống trong Python không?

Chỉ cần một danh sách trống ([]) cho con trỏ.fetchall () và không có danh sách nào cho con trỏ.fetchone ().Đối với bất kỳ tuyên bố nào khác, ví dụ:Chèn hoặc cập nhật, không trả về một bản ghi, bạn không thể gọi fetchall () cũng như fetchone () trên con trỏ. fetchall() and None for cursor. fetchone() . For any other statement, e.g. INSERT or UPDATE , that doesn't return a recordset, you can neither call fetchall() nor fetchone() on the cursor.

Làm thế nào để bạn kiểm tra xem kết quả SQL có trống không?

Tìm hiểu mysql từ đầu cho khoa học dữ liệu và phân tích mysql> chọn * từ cộtValuenULLDEMO trong đó cộtName là null hoặc cộtName = '';Sau khi thực hiện truy vấn trên, đầu ra thu được là.Đầu ra này được lấy là điều kiện thứ hai là đúng đối với giá trị trống.mysql> SELECT * FROM ColumnValueNullDemo WHERE ColumnName IS NULL OR ColumnName = ' '; After executing the above query, the output obtained is. This output was obtained as the second condition is true for empty value.

Fetchone () trong Python là gì?

fetchone () Phương thức này lấy hàng tiếp theo của bộ kết quả truy vấn và trả về một chuỗi duy nhất hoặc không có nếu không có thêm hàng.Theo mặc định, bộ tuple được trả về bao gồm dữ liệu được trả về bởi máy chủ MySQL, được chuyển đổi thành các đối tượng Python.retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available. By default, the returned tuple consists of data returned by the MySQL server, converted to Python objects.