| 320 | | # Add the newly created or already existing objects to the join table. |
|---|
| 321 | | # First find out which items are already added, to avoid adding them twice |
|---|
| 322 | | new_ids = set([obj._get_pk_val() for obj in objs]) |
|---|
| 323 | | cursor = connection.cursor() |
|---|
| 324 | | cursor.execute("SELECT %s FROM %s WHERE %s = %%s AND %s IN (%s)" % \ |
|---|
| 325 | | (target_col_name, self.join_table, source_col_name, |
|---|
| 326 | | target_col_name, ",".join(['%s'] * len(new_ids))), |
|---|
| 327 | | [self._pk_val] + list(new_ids)) |
|---|
| 328 | | if cursor.rowcount is not None and cursor.rowcount != 0: |
|---|
| 329 | | existing_ids = set([row[0] for row in cursor.fetchmany(cursor.rowcount)]) |
|---|
| 330 | | else: |
|---|
| 331 | | existing_ids = set() |
|---|
| 332 | | |
|---|
| 333 | | # Add the ones that aren't there already |
|---|
| 334 | | for obj_id in (new_ids - existing_ids): |
|---|
| 335 | | cursor.execute("INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % \ |
|---|
| 336 | | (self.join_table, source_col_name, target_col_name), |
|---|
| 337 | | [self._pk_val, obj_id]) |
|---|
| 338 | | transaction.commit_unless_managed() |
|---|
| | 320 | # If there aren't any objects, there is nothing to do. |
|---|
| | 321 | if objs: |
|---|
| | 322 | # Add the newly created or already existing objects to the join table. |
|---|
| | 323 | # First find out which items are already added, to avoid adding them twice |
|---|
| | 324 | new_ids = set([obj._get_pk_val() for obj in objs]) |
|---|
| | 325 | cursor = connection.cursor() |
|---|
| | 326 | cursor.execute("SELECT %s FROM %s WHERE %s = %%s AND %s IN (%s)" % \ |
|---|
| | 327 | (target_col_name, self.join_table, source_col_name, |
|---|
| | 328 | target_col_name, ",".join(['%s'] * len(new_ids))), |
|---|
| | 329 | [self._pk_val] + list(new_ids)) |
|---|
| | 330 | if cursor.rowcount is not None and cursor.rowcount != 0: |
|---|
| | 331 | existing_ids = set([row[0] for row in cursor.fetchmany(cursor.rowcount)]) |
|---|
| | 332 | else: |
|---|
| | 333 | existing_ids = set() |
|---|
| | 334 | |
|---|
| | 335 | # Add the ones that aren't there already |
|---|
| | 336 | for obj_id in (new_ids - existing_ids): |
|---|
| | 337 | cursor.execute("INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % \ |
|---|
| | 338 | (self.join_table, source_col_name, target_col_name), |
|---|
| | 339 | [self._pk_val, obj_id]) |
|---|
| | 340 | transaction.commit_unless_managed() |
|---|