How many lines were deleted?

Is it possible to check how many rows were deleted by the query?

queryset = MyModel.object.filter(foo=bar) queryset.delete() deleted = ... 

Or use transactions to do this?

 @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()); 
+6
django mysql django-models django-orm
source share
3 answers

I do not understand why queryset.count() or queryset.distinct().count() not enough.

0
source share

There are many situations where you want to know how many lines were deleted, for example, if you do something based on how many lines were deleted. Validation by its implementation COUNT creates additional load on the database and is not atomic.

The queryset.delete() method immediately deletes the object and returns the number of deleted objects and a dictionary with the number of deletes by type of object. Check the docs for more details: https://docs.djangoproject.com/en/1.9/topics/db/queries/#deleting-objects

+2
source share

The actual rows you could look at can be viewed with SELECT row_count() . First of all, qs.count() and cursor.rowcount are not the same!

In MySQL with InnoDB with REPEATABLE READ (default mode) READ queries and WRITE queries look at queries !! DIFFERENT !!! !

READ requests read from an old snapshot while WRITE requests look at the actual data, for example, they work in READ COMMITTED mode.

0
source share

All Articles