Django

Code

Changeset 4233

Show
Ignore:
Timestamp:
12/20/06 08:06:27 (2 years ago)
Author:
russellm
Message:

Refactored workhorse methods on m2m descriptors. Modified _add to check for the type of incoming objects (to match existing _remove implementation), and modified _remove to use a single query rather than 1 per object (to match existing _add implementation).

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/db/models/fields/related.py

    r4232 r4233  
    320320            # If there aren't any objects, there is nothing to do. 
    321321            if objs: 
     322                # Check that all the objects are of the right type 
     323                for obj in objs: 
     324                    if not isinstance(obj, self.model): 
     325                        raise ValueError, "objects to add() must be %s instances" % self.model._meta.object_name 
    322326                # Add the newly created or already existing objects to the join table. 
    323327                # First find out which items are already added, to avoid adding them twice 
     
    346350            from django.db import connection 
    347351 
    348             for obj in objs: 
    349                 if not isinstance(obj, self.model): 
    350                     raise ValueError, "objects to remove() must be %s instances" % self.model._meta.object_name 
    351             # Remove the specified objects from the join table 
    352             cursor = connection.cursor() 
    353             for obj in objs: 
    354                 cursor.execute("DELETE FROM %s WHERE %s = %%s AND %s = %%s" % \ 
    355                     (self.join_table, source_col_name, target_col_name), 
    356                     [self._pk_val, obj._get_pk_val()]) 
    357             transaction.commit_unless_managed() 
     352            # If there aren't any objects, there is nothing to do. 
     353            if objs: 
     354                # Check that all the objects are of the right type 
     355                for obj in objs: 
     356                    if not isinstance(obj, self.model): 
     357                        raise ValueError, "objects to remove() must be %s instances" % self.model._meta.object_name 
     358                # Remove the specified objects from the join table 
     359                old_ids = set([obj._get_pk_val() for obj in objs]) 
     360                cursor = connection.cursor() 
     361                cursor.execute("DELETE FROM %s WHERE %s = %%s AND %s IN (%s)" % \ 
     362                    (self.join_table, source_col_name,  
     363                    target_col_name, ",".join(['%s'] * len(old_ids))), 
     364                    [self._pk_val] + list(old_ids)) 
     365                transaction.commit_unless_managed() 
    358366 
    359367        def _clear_items(self, source_col_name):