删除了多少行?
是否可以检查查询删除了多少行?
queryset = MyModel.object.filter(foo=bar)
queryset.delete()
deleted = ...
或者我应该使用交易来实现这一点?
@transaction.commit_on_success
def delete_some_rows():
queryset = MyModel.object.filter(foo=bar)
deleted = queryset.count()
queryset.delete()
PHP + MySQL 示例:
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());
Is it possible to check how many rows were deleted by a query?
queryset = MyModel.object.filter(foo=bar)
queryset.delete()
deleted = ...
Or should I use transactions for that?
@transaction.commit_on_success
def delete_some_rows():
queryset = MyModel.object.filter(foo=bar)
deleted = queryset.count()
queryset.delete()
PHP + MySQL example:
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在很多情况下,您想知道删除了多少行,例如,如果您根据删除的行数执行某些操作。通过执行 COUNT 检查它会创建额外的数据库负载,并且不是原子的。
queryset.delete()
方法立即删除对象并返回已删除对象的数量以及包含每种对象类型的删除次数的字典。检查文档以获取更多详细信息:https://docs。 djangoproject.com/en/stable/topics/db/queries/#deleting-objects
There are many situations where you want to know how many rows were deleted, for example if you do something based on how many rows were deleted. Checking it by performing a COUNT creates extra database load and is not atomic.
The
queryset.delete()
method immediately deletes the object and returns the number of objects deleted and a dictionary with the number of deletions per object type.Check the docs for more details: https://docs.djangoproject.com/en/stable/topics/db/queries/#deleting-objects
您可以使用
SELECT row_count()
查看受影响的实际行数。首先,
qs.count()
和cursor.rowcount
不是同一件事!在 MySQL 和 InnoDB 中,具有可重复读取(默认模式)的读取查询和写入查询视图!!不同!!!查询集!
READ 查询从旧快照中读取,而 WRITE 查询则查看实际提交的数据,就像它们在 READ COMMITTED 模式下工作一样。
Actual rows affected you could view with
SELECT row_count()
.First of all
qs.count()
andcursor.rowcount
is not same things!In MySQL with InnoDB with REPEATABLE READ (default mode) READ queries and WRITE queries view !!DIFFERENT!!! querysets!
READ queries read from old snapshot, while WRITE queries view actual committed data, like they works in
READ COMMITTED
mode.