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')