删除了多少行?

发布于 2024-09-12 02:50:23 字数 487 浏览 5 评论 0原文

是否可以检查查询删除了多少行?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月苍老的讽刺 2024-09-19 02:50:23

在很多情况下,您想知道删除了多少行,例如,如果您根据删除的行数执行某些操作。通过执行 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

執念 2024-09-19 02:50:23

您可以使用 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() and cursor.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文