问题
I have a problem with MySQL 5.5 INSERT ... ON DUPLICATE KEY UPDATE
rows effected mismatch cursor.rowcount in a normal Django project
According to doc:
For INSERT ... ON DUPLICATE KEY UPDATE statements, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag, the affected-rows value is 1 (not 0) if an existing row is set to its current values.
So I tried in out, it seems that in mysql shell, repeating the INSERT ... ON DUPLICATE KEY UPDATE
statement will show
Query OK, 0 rows affected (0.00 sec)
In mysql-python (import MySQLdb),
cursor.rowcount
will always be 1 regardless of insert/update/nothing updated
I searched everywhere and can not find a way to change the CLIENT_FOUND_ROWS
flag in Django. Anyone know how?
回答1:
Okay, I found out how.
In django/db/backends/mysql/base.py there's
kwargs['client_flag'] = CLIENT.FOUND_ROWS
kwargs.update(settings_dict['OPTIONS'])
From the source code we could just change django project settings.py like this
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
'OPTIONS': {
'client_flag': 0
}
}
}
来源:https://stackoverflow.com/questions/19062530/change-client-found-rows-flag-in-django-for-mysql-python-mysqldb