Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Perform Raw SQL Update/Delete and return row count

Tags:

mysql

django

Going off the documentation here: http://docs.djangoproject.com/en/dev/topics/db/sql/

>>>cursor = connection.cursor()
>>>cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
>>>print cursor.fetchone()
None

Does anyone know how to return the modified row count?

(NOTE: I've played around with the placement/order of transaction.commit_unless_managed() and cursor.fetchone() (also cursor.fetchall()) and it doesn't seem to make a difference)

Thanks! -Tom

like image 612
TomFuertes Avatar asked Jun 09 '09 19:06

TomFuertes


1 Answers

An UPDATE statement as you've got in your example doesn't return row results, so fetchone() will always be empty (or might throw an error).

Use cursor.rowcount to get the rows last affected.

like image 65
Jarret Hardie Avatar answered Sep 18 '22 09:09

Jarret Hardie