侧边栏壁纸
  • 累计撰写 214 篇文章
  • 累计创建 59 个标签
  • 累计收到 5 条评论

查询集方法总览

barwe
2024-09-20 / 0 评论 / 0 点赞 / 64 阅读 / 5,376 字
温馨提示:
本文最后更新于 2024-09-20,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

数据库同步查询方式:

user = User.objects.get(pk=1)
users = User.objects.filter(is_active=True)

查询单个数据 Django 自带了异步方法(同步方法名前面加 a 即可):

user = await User.objects.aget(pk=1)

模型的数据库查询方法定义在 QuerySet 类上:

QuerySet

from django.db.models.query import QuerySet

实例查询

以下方法与模型实例的操作相关:

同步方法异步方法功能功能
iteratoraiteratorAn iterator over the results from applying this QuerySet to the database. chunk_size must be provided for QuerySets that prefetch.逐行遍历查询集
aggregateaaggregateReturn a dictionary containing the calculations (aggregation) over the current queryset. If args is present the expression is passed as a kwarg using the Aggregate object's default alias.计算查询集的总和、平均值、计数等统计信息
countacountPerform a SELECT COUNT() and return the number of records as an integer. If the QuerySet is already fully cached, return the length of the cached results set to avoid multiple SELECT COUNT(*) calls.查询集包含的实例数目
getagetPerform the query and return a single object matching the given keyword arguments.查询单个对象
createacreateCreate a new object with the given kwargs, saving it to the database and returning the created object.创建单个对象
bulk_createabulk_createInsert each of the instances into the database. Do not call save() on each of the instances, do not send any pre/post_save signals, and do not set the primary key attribute if it is an autoincrement field (except if features.can_return_rows_from_bulk_insert=True). Multi-table models are not supported.
bulk_updateabulk_updateUpdate the given fields in each of the given objects in the database.批量更新模型实例(效率更高)
get_or_createaget_or_createLook up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created.查询单个实例,不存在时创建它
update_or_createaupdate_or_createLook up an object with the given kwargs, updating one with defaults if it exists, otherwise create a new one. Optionally, an object can be created with different values than defaults by using create_defaults. Return a tuple (object, created), where created is a boolean specifying whether an object was created.实例存在时,更新它,否则创建它
earliestaearliestReturn the earliest object according to fields (if given) or by the model's Meta.get_latest_by.与时间字段一起使用,查询最早的实例
latestalatestReturn the latest object according to fields (if given) or by the model's Meta.get_latest_by.与时间字段一起使用,查询最新的实例
firstafirstReturn the first object of a query or None if no match is found.返回查询集的第一个实例,查询集为空时返回 None
lastalastReturn the last object of a query or None if no match is found.返回查询集的最后一个实例,查询集为空时返回 None
in_bulkain_bulkReturn a dictionary mapping each of the given IDs to the object with that ID. If id_list isn't provided, evaluate the entire QuerySet.根据指定的字段(通常是主键)快速地将查询集转换为字典格式。
deleteadeleteDelete the records in the current QuerySet.删除查询集中的所有实例
updateaupdateUpdate all elements in the current QuerySet, setting all the given fields to the appropriate values.更新查询集中的所有实例
existsaexistsReturn True if the QuerySet would have any results, False otherwise.查询集中是否至少存在一个实例
containsacontainsReturn True if the QuerySet contains the provided obj, False otherwise.查询集中是否包含指定的实例
explainaexplainRuns an EXPLAIN on the SQL query this QuerySet would perform, and returns the results.数据库将如何执行该查询的计划

子查询集

以下方法与查询子集相关:

方法功能功能
raw 执行原始 SQL 查询,并将结果转换为模型实例。这对于需要执行复杂的 SQL 查询或利用数据库特定功能时非常有用。
values 返回一个字典列表,每个字典对应查询集中的一条记录,字典的键是字段名,值是字段对应的值。这在需要获取部分字段而不需要完整模型实例时特别有用。
values_list 返回的结果是一个元组列表,而不是字典或模型实例,适合于需要简单数据结构的情况。
datesReturn a list of date objects representing all available dates for the given field_name, scoped to 'kind'.从日期字段中提取独特的日期值。这对于需要按日期进行分组或过滤时特别有用。
datetimesReturn a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'.
noneReturn an empty QuerySet.

以下方法返回查询子集:

方法
allReturn a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases.
filterReturn a new QuerySet instance with the args ANDed to the existing set.
excludeReturn a new QuerySet instance with NOT (args) ANDed to the existing set.
union 并集
intersection 交集
difference 差集
select_for_updateReturn a new QuerySet instance that will select objects with a FOR UPDATE lock.用于在事务中锁定数据库行,以防止其他事务对这些行进行修改。这在处理并发写入时尤其重要,可以防止“丢失更新”问题。
select_relatedReturn a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. If select_related(None) is called, clear the list.用于优化数据库查询,通过一次性获取相关的外键对象,减少数据库查询次数。这在处理一对多或一对一关系时非常有用,可以提高查询性能。
prefetch_relatedReturn a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated. When prefetch_related() is called more than once, append to the list of prefetch lookups. If prefetch_related(None) is called, clear the list.用于优化多对多关系或一对多关系的查询。与 select_related() 不同,prefetch_related() 通过额外的查询来减少数据库访问次数,从而提高性能。
annotateReturn a query set in which the returned objects have been annotated with extra data or aggregations.用于在查询集中添加计算字段的方法。通过这个方法,你可以为每个返回的对象添加一个新的字段,该字段的值是根据其他字段计算得出的。这在进行聚合计算或对某些数据进行转换时非常有用。
aliasReturn a query set with added aliases for extra data or aggregations.用于创建别名的方法,它允许开发者在查询中为模型字段、表达式或查询集创建别名。这在需要清晰地组织和引用复杂查询时特别有用。
order_byReturn a new QuerySet instance with the ordering changed.
distinctReturn a new QuerySet instance that will select only distinct results.
extraAdd extra SQL fragments to the query.
reverseReverse the ordering of the QuerySet.
deferDefer the loading of data for certain fields until they are accessed. Add the set of deferred fields to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case removal all deferrals.用于优化查询性能,允许开发者在查询时指定不需要加载的字段。这样可以减少数据库返回的数据量,尤其在处理大字段时(如文本或二进制数据)非常有用。
onlyEssentially, the opposite of defer(). Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated.defer() 的反面。
usingSelect which database this QuerySet should execute against.选择执行的数据库。

其他

以下为属性方法:

  • ordered: 查询集是否已经排序
  • db: 数据库
0

评论区