Django- official website partially translated (1.11 version of the document) -QuerySet- field Find -06

In this paper the model layer of translation django official website QuerySet chapter

Issue: 1.11

Making queries query

Once you have created a data table model class, django will automatically give you some database abstraction API, allowing you to create, query, update, delete objects, the following will describe how to use the API (a web application as an example to expand)

First, create a table model class

To analyze their table relationships, will help to understand the following

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):              # __unicode__ on Python 2
        return self.headline

In django (ORM), and the mapping between database objects is python image, a table model class (class) that is representative of a table, an example of an object that is representative of a data record

Create an object (a data record)

To create a data object in django, simply instantiate him, passing the key parameter table model class, then call .save () method to save this object to the database can be

from blog.models import Blog

b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
b.save()

This is actually the code behind a database insert statement, django does not execute this statement directly, until you call .save () method (.save () does not return value)

Save the modified table object

Want to save an already altered the object, call .save () method to (update a record)

The following is an example of a Blog b5 table object model class, he has a corresponding record in the database, the following statement will modify his name attribute value, and then update it to the database to

b5.name = 'New name'
b5.save()  # 代码运行到这里才会进行数据库操作,真正地更新到数据库!

Save or many foreign key field Field ( ForeignKeyor ManyToManyFieldFields)

Foreign key field ForeignKey

Update a foreign key field in exactly the same wording and the general field, only need to assign the correct type of objects related to the field to, the following statement is to update the blog a property Entry model class instance of an object out of the entry (make sure the following Blog Entry and used to instantiate an object that already exists in the database, so we will check them out before the statement)

from blog.models import Blog, Entry

entry = Entry.objects.get(pk=1)  # 查出主键是 1 的 entry 对象(记录)
cheese_blog = Blog.objects.get(name="Cheddar Talk")
entry.blog = cheese_blog  # 将 blog 对象直接赋值给 entry 对象的 blog 属性(对象赋值给字段)
entry.save()  # 调用 .save() 方法

ManyToManyField

You want to save many to many fields, writing and foreign key field a little difference, use .add () method to record a relationship.

The following case examples joe Object Model Author table entry increased class object (plus the one corresponding relationship)

from blog.models import Author

joe = Author.objects.create(name="joe")  # 创建了一个 Author类的对象 joe, 它的 name 属性是 joe
entry.authors.add(joe)  # 给已经查出来了的 entry 对象增加...(建立关联关系)

Inserting a plurality of many to many fields

john = Author.objects.create(name="John")
paul = Author.objects.create(name="Paul")
george = Author.objects.create(name="George")
ringo = Author.objects.create(name="Ringo")
entry.authors.add(john, paul, george, ringo)

If you pass the object type is not correct, django will be thrown

note! The add method to explain (objects can be directly transmitted, if the value is to pass a tuple?)

...

Retrieving objects found objects (QuerySet)

Query object from the database, to construct a model class table by QuerySet Manager manager.

QuerySet represents a set of database and your target range, which may be 0, 1 or a plurality of filters, filters can narrow the query results based on parameters you give for the SQL, a QuerySet equivalent to a SELECT statement, a filter is equivalent to a restriction, such as WHERE or lIMIT.

We use a table model class Manager to construct (get) a QuerySet, each table model class has at least one Manager, he can directly call the object (a good package of), we can access it directly through the table model class, we like this:

Blog.objects
# 内部对应的是:<django.db.models.manager.Manager object at ...>
b = Blog(name='Foo', tagline='Bar')  # 表模型类实例化会返回实例化好的对象
b.objects  # 会报错 AttributeError: "Manager isn't accessible via Blog instances." --> Manager 不能通过 Blog 实例来访问

note:

Managers can only be accessed by the list-based model rather than the model class instances (objects)

You have to make clear that you are currently using an operating table or record level aspects of the operation (only the table levels have Manager)

Retrieving all objects to detect all objects

The easiest way to get all records Objects (QuerySet) from the table is to call .all () method on Manager

all_entries = Entry.objects.all()  # 查出 Entry 模型类对应表中的所有数据记录,是一个 QuerySet

Retrieving specific objects with filters through the filter to detect the specified object

.all () method returns objects in the database all the records but in general, we just need to check out a few of the objects inside.

Want to get such a small part of the object, we need to refine (constraints) initial QuerySet, to increase the filtering conditions QuerySet refinement of the two most common worded as follows:

filter(**kwargs)

A return in line with lookup parameters (conditions) of your given QuerySet (the condition of)

exclude(**kwargs)

A return does not meet the lookup parameters (conditions) you give the QuerySet (does not meet the criteria)

Find parameters (** kwargs) should conform Field lookups (lookup fields) format (day 55 blog there)

They are, for example, you want to get published in 2006 QuerySet blog entries, so to achieve through the filter:

Entry.objects.filter(pub_date__year=2006)
# 也可以这么写(使用 表模型类的 Manager 来调用 filter)
Entry.objects.all().filter(pub_date__year=2006)

Chain filter

QuerySet refinement of the result itself was a QuerySet, so we can subdivide the chain (screened again) it, such as:

Entry.objects.filter(
    headline__startswith='What'
).exclude(
    pub_date__gte=datetime.date.today()
).filter(
    pub_date__gte=datetime.date(2005, 1, 30)
)  # 不写成一行是这样看起来更清楚点

The final query above statement (meaning) are: to identify all the headline "What" beginning later today and the non-pub_date today, and pub_date in QuerySet after 2005-1-30 (contains records meet the conditions)

Vernacular point is : find out the title beginning with What, in 2005 January 30 date (day) of all books record (QuerySet)

QuerySet are isolated from each other (different from the objects)

Personal understanding: QuerySet is equivalent to the SQL statement, you can add conditions to produce a new statement, the new statement will not affect the old statement executed multiple times with a different QuerySet results are due to database records that meet the conditions less

Every time you QuerySet refinement, you will get a brand-new QuerySet, he is not bound to do with QuerySet before the subdivision of each other.

Every refinement creates a separate and unique QuerySet object, which can be used to store, use and reuse.

q1 = Entry.objects.filter(headline__startswith="What")
q2 = q1.exclude(pub_date__gte=datetime.date.today())
q3 = q1.filter(pub_date__gte=datetime.date.today())

The above three are independent QuerySet

The first QuerySet contains all of the article title (headline) What QuerySet object to the beginning of the (record collection of objects)

The second is a subset QuerySet (objects after re-screened) a first set of additional conditions: pub_date not (exclude) today or in the future - before> today and today

The third QuerySet is a subset of the set (plus conditions on the first condition), additional conditions: pub_date today or in the future

Not two (q2, q3) other effects of a QuerySet (q1).

QuerySet is inert (do not take the initiative to perform)

QuerySet is inert, created QuerySet behavior (the statement) does not involve any database operations.

You can give many, many superimposed QuerySet filter criteria, but will not be django to carry them until the QuerySet is evaluated (inspection, evaluation -?> Presumed to be traversed, values, translated into value seems a little more appropriate), take a look at the following example:

q = Entry.objects.filter(headline__startswith="What")
q = q.filter(pub_date__lte=datetime.date.today())
q = q.exclude(body_text__icontains="food")
print(q)

This looks like the implementation of several database operations? three times? Do not! In fact, it is only performed once, only execution in the last line print (q) the time to perform database operations. In general, the results will only QuerySet in you "visit" when they will be fetched from the database when you perform, QuerySet will come to value (by accessing the database When you do, the QuerySet is evaluated by accessing the database, does not turn out)

QuerySet allowed to trigger several cases actually perform database operations
  • Iteration (for loop through)
  • He added slicing step size, index value, get, all, first, etc.
  • When pikle serialization
  • Triggered __repr__() 或者 __str__()when
  • Triggered __len__() 或者 len()when
    • If you want to get a few pieces of data without the need to meet the conditions of other information, can be used .count()to more efficiently obtain the number of stripes
  • Use list()when cast into the list QuerySet
  • When turn into strong bool type or condition as if
    • If the query results QuerySet of at least one (data object), returns True, if no results, returns False
Caching and QuerySets cache and QuerySets

Each QuerySet contains a cache, to minimize the number of database access and know how it works allows you to write more efficient code.

QuerySet's cache (cache) is a newly created empty, the value QuerySet first execution (evaluatad) when the database query, the query results will be saved to the cache Django QuerySet's cache and returns the query result set out . Subsequent values ​​can reuse the cached results QuerySet.

# 下面的这两行代码会走两次数据库操作,很可能他们两次得到的数据是相同的。
# 为什么我们不避免它呢? --> 很可能两次查询请求之间可能有对象被删除或者新增,会造成两次结果不一致
print([e.headline for e in Entry.objects.all()])
print([e.pub_date for e in Entry.objects.all()])


# 下面的代码只会走一次数据库操作
queryset = Entry.objects.all()
print([p.headline for p in queryset]) # 真正地执行数据库操作
print([p.pub_date for p in queryset]) # 重用上一次查询出来的结果(cache)

When QuerySets are not cached situation does not save cache cache

He will not always QuerySet caching query results, only when needed (value) part of the result set, cache will be checked, but if not filled, subsequent queries will not be cached items returned ( but if it is not populated then the items returned by the subsequent query are not cached.), specific to , this means that the use of an array or slice index limit the query result set caching will not be saved.

For example, each time to obtain a clear index will perform a database operation

# 下面的操作执行了两次数据库查询
queryset = Entry.objects.all()
print(queryset[5]) # 查询数据库
print(queryset[5]) # 又一次查询了数据库

However, if the entire value has been QuerySet (evaluated), then the cache will be cached

# 下面的操作只执行了一次数据库查询
queryset = Entry.objects.all()
entry_list = [entry for entry in queryset] # 执行了数据库操作
print(queryset[5]) # 使用 cache
print(queryset[5]) # 使用 cache

Here are some values ​​can be whole (evaluated) some cases, you can save the data into the cache (cache so that subsequent use, reducing the number of database operations)

[entry for entry in queryset]
bool(queryset)
entry in queryset
list(queryset)

Be careful this feature , you can use it to improve the performance of the code (to reduce the number of inquiries, reducing database stress), but may also cause data disorder because with the cache (data not using the latest, to read between the occurrence of another modified once modified, this time using the data in the database has been updated over the (high concurrency is likely to occur),)!

Retrieving a single object with get()using the get () only takes a data object

. Filter () method returns a QuerySet, even if he only inside a data object, if you know the result of the query is only one object, you can use the Table Manager object model class to call the .get () method, incoming queries entered, contact condition to a data object.

one_entry = Entry.objects.get(pk=1)

You can use the .get () method behind any query, he could also receive some keyword arguments, also supports field find syntax (__gt = 18).

Remember this

Use .get()and .filter()[0]a bit different, the query result if the condition is not satisfied, and .get()will report a DoesNotExistfault, this error is a property sheet model being executed, so in the above code, if the Entry corresponding table without any objects that match a primary key is 1, then the error will django: Entry.DoesNotExist.

Similarly, if there are multiple objects at the same time satisfy this condition, it will django error: MultipleObjectsReturnedA model class attribute this error is performed.

Other QuerySet methods other QuerySet methods

Typically, you would use .all()、.get()、.exclude()to query the database, but we offer much more than that.

More details can be seen QuerySet API

Normally, when you use the combination of filter and other QuerySet will call chain, in order to achieve chained calls, most QuerySet method returns a new QuerySet

QuerySet class has two public properties can be used to reflect on you? (Use for introspection)

ordered

If the query results QuerySet are ordered, will return True, if it is disorderly, returns False

db

It will be used to perform database query statement

query

You can view the current QuerySet corresponding SQL statement

Methods that return new QuerySets method returns a new QuerySets

# 常见的几个
.filter(**kwargs) 符合条件的
.exclude(**kwargs) 不符合条件的
.annnotate(*args, **kwargs)  分组
.order_by(*fields) 排序
.reverse()  反序
.distinct(*fields) 去重
.values(*fields, **expressions*) 过滤字段
.values_list(*fields, flat=False) 过滤字段
.all()
.select_related(*field) 优化,可以把对象查出来,并附带字段,后期对象 .字段 不会再触发数据库操作
.prefetch_related(*lookups) 优化相关
.defer(*fields) 优化相关
.only(*fields) 优化相关
.select_for_update(nowait=False, skip_locked=False)

# 不常见的几个
.dates(field, kind, order=‘ASC’) 
.datetimes(field_name, kind, order=‘ASC’, tzinfo=None)
.none() 创建空的 QuerySet
.union(*other_qs, all=False) 
.intersection(*other_qs)
.difference(*other_qs)
.extra(一堆参数) 自定义SQL(将被舍弃的方法)
.extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
.using(alias)  多个数据库时指定数据库(数据库配置可以配好几个数据库连接)
.raw(raw_query, params=None, translations=None)
.filter (** kwargs) qualifying

Returns a new QuerySet, which contains the object is to satisfy the query parameters (conditions) you give, the more query (keyword) parameters separated by commas, corresponds to the SQL statement is AND connected, if you want to perform more complex operations (such as oR,) may be used Q Object

Use Q objects

from django.db.models import *
"""
, 间隔 Q 对象,是 and 关系 ( & 也是)
| 间隔 Q 对象,是 or  关系
~ 放在 Q 对象前面,是 ! 取反关系
"""

Poll.objects.get(
    Q(question__startswith='Who'),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
# --> SELECT * from polls WHERE question LIKE 'Who%' AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
.exclude (** kwargs) does not meet the conditions

QuerySet that returns a new, which contains the object does not satisfy the search criteria are specified in the parentheses, a plurality of queries (keywords) separated by commas parameter, the parameter is an AND relationship between, the outermost layer is a logical NOT ( ). If you want to perform more complex operations (such as OR or) you can use Q objects

Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello')
# 对应的SQL :SELECT ... WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')

# 同样他也支持像 filter 那样链式调用
Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello')
# 对应的SQL :SELECT ... WHERE NOT pub_date > '2005-1-3' AND NOT headline = 'Hello'
.annnotate (* args, ** kwargs) groups - temporary read
.order_by (* fields) sort - too long, first put
.reverse () Reverse Order

Only for the row over the sequence of QuerySet using ...

.distinct (* fields) to heavy
.values ​​(* fields, ** expressions *) filter field
.values_list (* fields, flat = False) filter field
.none () to create an empty QuerySet

Call .none () method creates an empty QuerySet that, which does not contain any data objects, and also does not perform any operations on the database when the value (is an example of EmptyQuerySet)

Entry.objects.none()
# <QuerySet []>


from django.db.models.query import EmptyQuerySet

isinstance(Entry.objects.none(), EmptyQuerySet)
# True

# 下面两句不会执行数据库操作
print(models.Book.objects.none())
# <QuerySet []>
print(models.Book.objects.none().filter(title__contains='三国'))
# <QuerySet []>
.all()
.union(*other_qs, all=False)
.intersection(*other_qs)
.difference(*other_qs)
.select_related (* field) optimization, can check out the object, and comes with a field, late objects. field will not trigger database operations
.prefetch_related (* lookups) optimization-related
.extra (a bunch of parameters) custom SQL (method will be discarded)

.extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)

.defer (* fields) related to optimization
.only (* fields) related to optimization
.using specified database (Alias) a plurality of databases (databases may be configured with several database connections)
.select_for_update(nowait=False, skip_locked=False)
.raw(raw_query, params=None, translations=None)

Methods that do not return QuerySets method does not return QuerySet object

The following QuerySet methods will directly trigger the database operations and then return some of the other things, not QuerySet

These methods do not use the buffer cache, on the contrary, each call they will perform database operations

# 常见的几个
.get(**kwargs) 返回当个对象
.create(**kwargs) 
.count()
.latest(field_name=None)
.earliest(field_name=None)
.first()
.last()
.aggregate(*args, **kwargs)
.exists()
.update(**kwargs)
.delete()

# 不常见的几个
.get_or_create(defaults=None, **kwargs)
.update_or_create(defaults=None, **kwargs)
.bulk_create(objs, batch_size=None)
.in_bulk(id_list=None)
.iterator()
.as_manager()
.get (** kwargs) returns when objects
.create(**kwargs)
.count()
.first()
.last()
.aggregate(*args, **kwargs)
.exists()
.update(**kwargs)
.delete()
.latest(field_name=None)
.earliest(field_name=None)

Aggregation functions aggregate functions

field-lookups lookup field (field query, double underline inquiry)

This part of the reference document: Django's official website to find field (field-lookups)

Find field (field-lookups) corresponds to the WHERE clause of the SQL statement, the object is generally placed in QuerySet filter (), exclude (), get () method, as a condition

Common forms

important point

Different databases support these different methods, django orm corresponding to different databases can be translated into different SQL statements

  • sqlite support unfriendly to date type, data (string) case-insensitive (ignore case)
  • python is not sensitive to floating point accuracy (price = 66.66 -> so there may be a record, but it does not match (python (like sqlite it) turned it into 66.651556464)?)

Writing format

field__lookuptype --> price_gt (Two underscores)

such as

# 省略一些要导入的文件
Entry.objects.filter(pub_date__lte='2006-01-01')

# 翻译成对应的 SQL 语句就是:
SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';

# pub_date__lte='2006-01-01' --> pub_date <= '2006-01-01'

Why the above table is blog_entry?

Table table with django model class created automatically prefixed with the app (obviously app here called blog)

lookuptype search type sort

This part of the pseudo-code that demonstrates the use of these fields only function queries and the corresponding SQL statement what

In this model table are directly the beginning of the class (equivalent from app01.models import *)

Comparison of class relations

__gt
# 字段大于...
Entry.objects.filter(id__gt=4)
# --> SELECT ... WHERE id > 4;

__gte
# 大于等于

__lt
# 小于

__lte
# 小于等于

__isnull
# 字段是否为空
Entry.objects.filter(pub_date__isnull=True)
# --> SELECT ... WHERE pub_date IS NULL;

Fuzzy matching class, regular

Precision is a direct match = / exact

# --------- 是否包含 --------------
__contains
# 字段值是否包含 __ 
Entry.objects.get(headline__contains='Lennon')
# --> SELECT ... WHERE headline LIKE '%Lennon%';

__icontains
# 字段值是否包含 __ ,忽略大小写的包含
Entry.objects.get(headline__icontains='Lennon')
# --> SELECT ... WHERE headline ILIKE '%Lennon%';

# --------- 以 ... 开头 或 结尾 --------------
__startswith
# 字段以 __ 开头
Entry.objects.filter(headline__startswith='Lennon')
# --> SELECT ... WHERE headline LIKE 'Lennon%';

__istartswith
# 字段以 __ 开头,忽略大小写
Entry.objects.filter(headline__istartswith='Lennon')
# --> SELECT ... WHERE headline ILIKE 'Lennon%';

__endswith
# 字段以 __ 结尾
Entry.objects.filter(headline__endswith='Lennon')
# --> SELECT ... WHERE headline LIKE '%Lennon';

__iendswith
# 字段以 __ 结尾,忽略大小写
Entry.objects.filter(headline__iendswith='Lennon')
# --> SELECT ... WHERE headline ILIKE '%Lennon'

# --------- 全文检索 --------------
__search
# 全文检索(django 1.10 开始有改动)
Entry.objects.filter(headline__search="+Django -jazz Python")
# --> SELECT ... WHERE MATCH(tablename, headline) AGAINST (+Django -jazz Python IN BOOLEAN MODE);

# --------- 正则相关 --------------
__regex
# 正则匹配
Entry.objects.get(title__regex=r'^(An?|The) +')
# --> SELECT ... WHERE title REGEXP BINARY '^(An?|The) +';  # -- MySQL,对于这个字段查询,django orm 对应不同的 数据库 会解析成不同的 SQL 语句

__iregex
# 忽略大小写的正则匹配
# 案例
Entry.objects.get(title__iregex=r'^(an?|the) +')
# -->SELECT ... WHERE title REGEXP '^(an?|the) +';

Class range

__in
# 字段的值在不在给定的列表范围内
Entry.objects.filter(id__in=[1, 3, 4])
# --> SELECT ... WHERE id IN (1, 3, 4);

# 补充:也可以使用会动态的查询 QuerySet 作为列表
inner_qs = Blog.objects.filter(name__contains='Cheddar')
entries = Entry.objects.filter(blog__in=inner_qs)
# --> SELECT ... WHERE blog.id IN (SELECT id FROM ... WHERE NAME LIKE '%Cheddar%')

__range
# 可以比较日期时间、数字范围、字符(串?没验证)范围
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))
# --> SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';

Date Time Class

Date Time and date can not be mixed

Allow to find other relations class field (field-lookups, greater than less than this) chain stitching

__date
# 匹配 datetime 类型字段,会将传入的值转换为日期,然后搭配 关系类的字段查找(field-lookups)进行比较
Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
# --> ...

__year
# 匹配 datetime、date 类型字段,直接指定精确的哪一年
Entry.objects.filter(pub_date__year=2005)
# --> SELECT ... WHERE pub_date BETWEEN '2005-01-01' AND '2005-12-31';
Entry.objects.filter(pub_date__year__gte=2005)
# --> SELECT ... WHERE pub_date >= '2005-01-01';

__month
# 匹配 datetime、date 类型字段,范围是 1 (January) --- 12 (December),语句视数据库引擎而定    
Entry.objects.filter(pub_date__month=12)
# --> SELECT ... WHERE EXTRACT('month' FROM pub_date) = '12';
Entry.objects.filter(pub_date__month__gte=6)
# --> SELECT ... WHERE EXTRACT('month' FROM pub_date) >= '6';

__day
# 匹配 datetime、date 类型字段,当月的第几天
Entry.objects.filter(pub_date__day=3)
# --> SELECT ... WHERE EXTRACT('day' FROM pub_date) = '3';
Entry.objects.filter(pub_date__day__gte=3)
# --> SELECT ... WHERE EXTRACT('day' FROM pub_date) >= '3';
# Note this will match any record with a pub_date on the third day of the month, such as January 3, July 3, etc.

__week
# 匹配 datetime、date 类型字段,当年的第几周(1-52/53,平闰年不同)
# django 1.11 中新增的
Entry.objects.filter(pub_date__week=52)
Entry.objects.filter(pub_date__week__gte=32, pub_date__week__lte=38)
# --> ...
# return the week number (1-52 or 53) according to ISO-8601, i.e., weeks start on a Monday and the first week starts on or before Thursday.

__week_day
# 匹配 datetime、date 类型字段 范围:1 (Sunday) -- 7 (Saturday)
Entry.objects.filter(pub_date__week_day=2)
Entry.objects.filter(pub_date__week_day__gte=2)
# --> ...

__time
# 匹配 datetime、time 类型字段的 minute, django 1.11 中新增的
Entry.objects.filter(pub_date__time=datetime.time(14, 30))
# 实现方式取决于数据库引擎(暂时没有例子)


__hour
# 匹配 datetime、time 类型字段的 minute,范围 0-23
Event.objects.filter(timestamp__hour=23)
# --> SELECT ... WHERE EXTRACT('hour' FROM timestamp) = '23';


__minute
# 匹配 datetime、time 类型字段的 minute,范围 0-59
Event.objects.filter(timestamp__minute=29)
# --> SELECT ... WHERE EXTRACT('minute' FROM timestamp) = '29';

__second
# datetime、time 类型字段相关的,看不太懂
Event.objects.filter(timestamp__second=31)
# --> SELECT ... WHERE EXTRACT('second' FROM timestamp) = '31';
# 文档:
# For datetime and time fields, an exact second match. Allows chaining additional field lookups. Takes an integer between 0 and 59.
# For datetime fields, when USE_TZ is True, values are converted to the current time zone before filtering.

Custom Field lookup (custom field-lookups)

These general official has been completely enough, really want to customize the documentation to go and see

word

Behind each translation document written down for easy viewing

Subsequent re-integrated into a blog, you can attach occurrences of the word whole sentence, translated, this meaningful learning English will be more clear and effective, to use the document to see the accumulation of words

lookuptype      查找类型
refine          细分、精细化(缩小范围)
brand-new       崭新的
in no way       绝对不
separate        独立的...
stored          存储
reuse           重用
an additional criteria      附加条件
the act of      ...的行为
involve         涉及
stack ... together      将...叠加在一起
evaluated       (检查,评估?--> 推测是 遍历、取值,翻译成取值好像更合适一点)
alias           别名

In particular point

Stored foreign key fields there may be directly assigned to a key object foreign objects (blog Object -> blog Properties)

cache mechanism

Guess you like

Origin www.cnblogs.com/suwanbin/p/11570151.html