Ticket #5390: related.diff

File related.diff, 2.7 KB (added by Ludovico Magnocavallo <ludo@…>, 17 years ago)

Cleaner variant of patch #2

  • db/models/signals.py

     
    1010post_delete = object()
    1111
    1212post_syncdb = object()
     13
     14m2m_add_items = object()
     15
     16m2m_remove_items = object()
     17
     18m2m_clear_items = object()
  • db/models/fields/related.py

     
    22from django.db.models import signals, get_model
    33from django.db.models.fields import AutoField, Field, IntegerField, PositiveIntegerField, PositiveSmallIntegerField, get_ul_class
    44from django.db.models.related import RelatedObject
     5from django.db.models import signals
     6from django.dispatch import dispatcher
    57from django.utils.text import capfirst
    68from django.utils.translation import ugettext_lazy, string_concat, ungettext, ugettext as _
    79from django.utils.functional import curry
     
    339341                existing_ids = set([row[0] for row in cursor.fetchall()])
    340342
    341343                # Add the ones that aren't there already
    342                 for obj_id in (new_ids - existing_ids):
     344                new_ids = new_ids - existing_ids
     345                for obj_id in new_ids:
    343346                    cursor.execute("INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % \
    344347                        (self.join_table, source_col_name, target_col_name),
    345348                        [self._pk_val, obj_id])
     349                       
     350                added_objs = [obj for obj in objs if (isinstance(obj, self.model) and obj._get_pk_val() in new_ids) or obj in new_ids]
     351                dispatcher.send(signal=signals.m2m_add_items, sender=self.model, instance=self.instance, objs=added_objs)
     352                       
    346353                transaction.commit_unless_managed()
    347354
    348355        def _remove_items(self, source_col_name, target_col_name, *objs):
     
    365372                    (self.join_table, source_col_name,
    366373                    target_col_name, ",".join(['%s'] * len(old_ids))),
    367374                    [self._pk_val] + list(old_ids))
     375                dispatcher.send(signal=signals.m2m_remove_items, sender=self.model, instance=self.instance, objs=objs)
    368376                transaction.commit_unless_managed()
    369377
    370378        def _clear_items(self, source_col_name):
    371379            # source_col_name: the PK colname in join_table for the source object
     380            dispatcher.send(signal=signals.m2m_clear_items, sender=self.model, instance=self.instance)
    372381            cursor = connection.cursor()
    373382            cursor.execute("DELETE FROM %s WHERE %s = %%s" % \
    374383                (self.join_table, source_col_name),
Back to Top