问题
I am trying to use the m2m_changed signal to trigger some actions in my application
. However, the printout of signaltest()
indicates that I am only signalled on pre_clear
and post_clear
actions. My models.py
looks like this:
class Entry(models.Model):
objects = managers.MyEntryManager()
...
fields = models.ManyToManyField('Field', through='EntryField')
class Field(models.Model):
name = models.CharField(max_length=64, unique=True)
description = models.CharField(max_length=256, blank=True)
class EntryField(models.Model):
entry = models.ForeignKey('Entry')
field = models.ForeignKey('Field')
value = models.CharField(max_length=256)
def signaltest(**kwargs):
print kwargs['action']
signals.m2m_changed.connect(signaltest, sender=Entry.fields.through, weak=False, dispatch_uid='signaltest')
The EntryField
objects are created elsewhere in the code using the following code:
some_entry.fields.clear()
models.EntryField.objects.get_or_create(
entry=some_entry,
field=some_field,
defaults = { 'value': field_value }
)
The first call is responsible for the pre_clear
and post_clear
events I receive. However, the second call generates no signals.
It seems to me that django bug #13757 is related to this (mis)behaviour, but I may be missing something.
Is there a way to "rewire" the signals (perhaps using some signal other than m2m_changed
) to have post_save
signals generated when a EntryField
is created?
回答1:
could you please try this out?
def signaltest(**kwargs):
print kwargs['instance']
print kwargs['created']
signals.post_save.connect(signaltest, sender=EntryField, weak=False, dispatch_uid='signaltest')
来源:https://stackoverflow.com/questions/12689721/django-m2m-changed-signal-with-custom-through-model