Field query parameters and aggregation functions of Django model layer

This series of tutorials is a personal original, and is fully published on the personal official website Liu Jiang's blog and tutorials

All those who reprint this article must indicate the original author and the official website address of www.liujiangblog.com in a prominent position at the top.


Field query refers to how to specify the contents of the SQL WHERE clause. They are used as keyword arguments to QuerySet's filter(), exclude() and get() methods.

The default lookup type is exact.


The following table lists all field query parameters:

field name illustrate
exact exact match
iexact Case-insensitive exact match
contains contains matches
icontains Case-insensitive containment match
in matches within
gt more than the
gte greater or equal to
lt less than
lte less than or equal to
startswith match from the beginning
istartswith Case-insensitive match from the beginning
endswith match from the end
iendswith Case-insensitive match from the end
range range match
date date match
year years
month month
day date
week which week
week_day which day
time time
hour Hour
minute minute
second Second
isnull Determine if it is empty
search Deprecated in 1.10
regex case-sensitive regular matching
iregex Case-insensitive regular matching

1. exact

Exact match. Default lookup type!

Entry.objects.get(id__exact=14)
Entry.objects.get(id__exact=None)

2. iexact

Case-insensitive exact match.

Blog.objects.get(name__iexact='beatles blog')
Blog.objects.get(name__iexact=None)

The first query will match 'Beatles Blog', 'beatles blog', 'BeAtLes BLoG' and so on.

3. contains

Case-sensitive containment matching.

Entry.objects.get(headline__contains='Lennon')

This will match the title 'Lennon honored today', but not 'lennon honored today'.

4. icontains

Case-insensitive containment matching.

Entry.objects.get(headline__icontains='Lennon')

5. in

Find in the given list.

Entry.objects.filter(id__in=[1, 3, 4])

Instead of providing a list of literal values, you can also use a dynamic queryset:

inner_qs = Blog.objects.filter(name__contains='Cheddar')
entries = Entry.objects.filter(blog__in=inner_qs)

Or values_list()the QuerySet obtained from values() or as the object of the comparison:

inner_qs = Blog.objects.filter(name__contains='Ch').values('name')
entries = Entry.objects.filter(blog__name__in=inner_qs)

The following example will generate an exception because an attempt is made to extract the value of two fields, but the query only needs the value of one field:

# 错误的实例,将弹出异常。
inner_qs = Blog.objects.filter(name__contains='Ch').values('name', 'id')
entries = Entry.objects.filter(blog__name__in=inner_qs)

6. gt

more than the

Entry.objects.filter(id__gt=4)

7. gte

greater than or equal to

8. lt

less than

9. lte

less than or equal to

10. startswith

Case sensitive, match from start position.

Entry.objects.filter(headline__startswith='Lennon')

11. istartswith

Case-insensitive, matches from the beginning.

Entry.objects.filter(headline__istartswith='Lennon')

12. endswith

Case-sensitive, matches starting with the end unknown.

Entry.objects.filter(headline__endswith='Lennon')

13. iendswith

Case-insensitive, matches starting with the end unknown.

Entry.objects.filter(headline__iendswith='Lennon')

14. range

Range testing (included).

import datetime
start_date = datetime.date(2005, 1, 1)
end_date = datetime.date(2005, 3, 31)
Entry.objects.filter(pub_date__range=(start_date, end_date))

Warning: Filtering a DateTimeField with dates will not include the last day, as the boundary is interpreted as "0am on a given date".

15. date

Do a date comparison.

Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))

When USE_TZTrue, the field will be converted to the current timezone and then filtered.

16. year

Match the year.

Entry.objects.filter(pub_date__year=2005)
Entry.objects.filter(pub_date__year__gte=2005)

When USE_TZTrue, datetime fields will be converted to the current time zone before filtering.

17. month

Match months. Round from 1 (January) to 12 (December).

Entry.objects.filter(pub_date__month=12)
Entry.objects.filter(pub_date__month__gte=6)

When USE_TZ is True, datetime fields are converted to the current time zone before filtering.

18. day

Matches to a specific day.

Entry.objects.filter(pub_date__day=3)
Entry.objects.filter(pub_date__day__gte=3)

When USE_TZ is True, datetime fields are converted to the current time zone before filtering.

19. week

New in Django 1.11. Returns the week number (1-52 or 53) according to ISO-8601, the week starting on Monday, Thursday or the first week before.

Entry.objects.filter(pub_date__week=52)
Entry.objects.filter(pub_date__week__gte=32, pub_date__week__lte=38)

When USE_TZ is True, the field is converted to the current timezone and then filtered.

20. week_day

Do a "day of the week" match. Takes an integer value, 1 for Sunday, 2 for Monday, and 7 for Saturday.

Entry.objects.filter(pub_date__week_day=2)
Entry.objects.filter(pub_date__week_day__gte=2)

When USE_TZ is True, datetime fields are converted to the current time zone before filtering.

21. time

New in Django 1.11.

Convert the field value to datetime.time format and compare.

Entry.objects.filter(pub_date__time=datetime.time(14, 30))
Entry.objects.filter(pub_date__time__between=(datetime.time(8), datetime.time(17)))

When USE_TZ is True, the field is converted to the current time zone and then filtered.

22. hour

Match hours. Take an integer between 0 and 23.

Event.objects.filter(timestamp__hour=23)
Event.objects.filter(time__hour=5)
Event.objects.filter(timestamp__hour__gte=12)

When USE_TZ is True, the value will be converted to the current time zone before filtering.

23. minute

Match on minutes. Take an integer between 0 and 59.

Event.objects.filter(timestamp__minute=29)
Event.objects.filter(time__minute=46)
Event.objects.filter(timestamp__minute__gte=29)

When USE_TZ is True, the value will be converted to the current time zone before being filtered.

24. second

Match on seconds. Take an integer between 0 and 59.

Event.objects.filter(timestamp__second=31)
Event.objects.filter(time__second=2)
Event.objects.filter(timestamp__second__gte=31)

When USE_TZ is True, the value will be converted to the current time zone before filtering.

25. isnull

The value is False or True, equivalent to the SQL statements IS NULL and IS NOT NULL.

Entry.objects.filter(pub_date__isnull=True)

Deprecated since version 1.10.

27. regex

Case-sensitive regular expression matching.

Entry.objects.get(title__regex=r'^(An?|The) +')

It is recommended to use raw strings (for example, r'foo' instead of 'foo' ) to pass regular expression syntax.

28. iregex

Case-insensitive regular expression matching.

Entry.objects.get(title__iregex=r'^(an?|the) +')

Aggregate function

Django's django.db.modelsmodules provide the following aggregate functions.

1. expression

A string referencing a model field, or a query expression.

2. output_field

The model field used to represent the return value, an optional parameter.

3.**extra

Keyword arguments can provide additional information to the SQL generated by aggregate functions.

4. Avg

class Avg(expression, output_field=FloatField(), **extra)[source]

Returns the average of the given expression, which must be numeric unless specified differently output_field.

默认的别名:<field>__avg
返回类型:float(或指定任何output_field的类型)

5. Count

class Count(expression, distinct=False, **extra)[source]

Returns the number of objects associated with expression.

默认的别名:<field>__count
返回类型:int
有一个可选的参数:distinct。如果distinct=True,Count 将只计算唯一的实例。默认值为False。

6. Max

class Max(expression, output_field=None, **extra)[source]

Returns the maximum value of expression.

默认的别名:<field>__max
返回类型:与输入字段的类型相同,如果提供则为`output_field`类型

7. Min

class Min(expression, output_field=None, **extra)[source]

Returns the minimum value of expression.

默认的别名:<field>__min
返回类型:与输入字段的类型相同,如果提供则为`output_field`类型

8. StdDev

class StdDev(expression, sample=False, **extra)[source]

Returns the standard deviation of expression.

默认的别名:<field>__stddev
返回类型:float
有一个可选的参数:sample。默认情况下,返回群体的标准差。如果sample=True,返回样本的标准差。
SQLite 没有直接提供StdDev。

9. Sum

class Sum(expression, output_field=None, **extra)[source]

Calculates the sum of all values ​​of expression.

默认的别名:<field>__sum
返回类型:与输入字段的类型相同,如果提供则为output_field类型

10. Variance

class Variance(expression, sample=False, **extra)[source]

Returns the variance of expression.

默认的别名:<field>__variance
返回类型:float
有一个可选的参数:sample。
SQLite 没有直接提供Variance。

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326624210&siteId=291194637