views:

55

answers:

1

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());
A: 

I don't understand why queryset.count() or queryset.distinct().count() isn't enough.

the_void
It's enough, but it produces more queries. PHP+MySQL example is only singe request to DBMS. Also IMO PHP code is more explicit.I don't have performance problem or something, so I must do it in single query. I'm just curious.
Tomasz Wysocki
You can also have access to the `rowcount` attribute of the underlying `MySQLdb` cursor, but it's hack-ish: `base_cursor = connection.cursor().cursor` (or `base_cursor = connection.cursor().cursor.cursor` if `DEBUG` is set to `True`).
the_void
You have to understand that ORM you are using in Django is a abstraction layer higher then then the database driver which allows yours app to be database agnostic, but you can still use database driver to communicate with underlying database like you do in your PHP example, but you would make your app database dependant.
rebus
As I've said, using the underlying cursor is hack-ish and not recommended. There are however situations in which *tuning* Django's automatically-generated queries does improve performance. I would not do it unless there is no other way or the performance impact is really really great.
the_void