From e69b09a033424f07343ad253ecfee497fb7c405d Mon Sep 17 00:00:00 2001 From: Luke Plant Date: Tue, 7 Feb 2006 18:47:32 +0000 Subject: [PATCH] magic-removal: Fixed use of return value of cursor.execute() in m2m add() and added a test to make sure git-svn-id: http://code.djangoproject.com/svn/django/branches/magic-removal@2289 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/fields/related.py | 7 +++++-- tests/modeltests/many_to_many/models.py | 3 +++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 1abfabafea..311df991a4 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -123,11 +123,14 @@ def _add_m2m_items(rel_manager_inst, managerclass, rel_model, join_table, this_c # First find out which items are already added, to avoid adding them twice new_ids = set([obj._get_pk_val() for obj in objs]) cursor = connection.cursor() - rowcount = cursor.execute("SELECT %s FROM %s WHERE %s = %%s AND %s IN (%s)" % \ + cursor.execute("SELECT %s FROM %s WHERE %s = %%s AND %s IN (%s)" % \ (rel_col_name, join_table, this_col_name, rel_col_name, ",".join(['%s'] * len(new_ids))), [this_pk_val] + list(new_ids)) - existing_ids = set([row[0] for row in cursor.fetchmany(rowcount)]) + if cursor.rowcount is not None and cursor.rowcount > 0: + existing_ids = set([row[0] for row in cursor.fetchmany(cursor.rowcount)]) + else: + existing_ids = set() # Add the ones that aren't there already for obj_id in (new_ids - existing_ids): diff --git a/tests/modeltests/many_to_many/models.py b/tests/modeltests/many_to_many/models.py index 19fa58d033..014a2a060d 100644 --- a/tests/modeltests/many_to_many/models.py +++ b/tests/modeltests/many_to_many/models.py @@ -44,6 +44,9 @@ API_TESTS = """ >>> a2.publications.add(p1, p2) >>> a2.publications.add(p3) +# Adding a second time is OK +>>> a2.publications.add(p3) + # Add a Publication directly via publications.add by using keyword arguments. >>> a2.publications.add(title='Highlights for Children')