Changing many-to-many using Admin Site never calls post_remove Signal

13 views
Skip to first unread message

Tobias Dacoir

unread,
Jan 30, 2015, 3:44:29 PM1/30/15
to django...@googlegroups.com
I have a many-to-many relationship which the Admin can change using the Admin Site. I use a ModelAdmin.filter_horizontal, but even with the default widget it's the same.

I registered a receiver when m2m_changed, however it always only calls: pre_clear, post_clear, pre_add, post_add, in that order.

Now for post_add I have code to execute, to create new objects in the database, however when a value is removed from this many-to-many field, I need to delete some objects. Since pre_remove is never called, I can't tell which value was removed and I'm unable to find out which objects to delete.

Is there a way to modify the Admin page to actually call remove / add on the Model? Or I need another way to find out which value was removed.

Tobias Dacoir

unread,
Jan 30, 2015, 3:59:27 PM1/30/15
to django...@googlegroups.com
not very nice, and probably not pythonic (still learning) but now I added another two for loops to find old references and delete them:
    if action == "post_add":
       
if isinstance(instance, Database):
           
# then update pairs
           
for a in instance.audioData():
               
for q in instance.questions.all():
                    pair
= AudioQuestionPair.objects.get_or_create(audioData=a, question=q, database=instance)
                   
for choice in q.get_choices():
                        answer
= Answer.objects.get_or_create(body=choice, audioQuestionPair=pair[0])
       
# check for removed questions and delete pairs
        pairs
= AudioQuestionPair.objects.filter(database=instance)
        toDelete
= []
       
for pair in pairs:
           
if pair.question not in instance.questions.all():
                toDelete
.append(pair)
       
for item in toDelete:
            item
.delete()
Reply all
Reply to author
Forward
0 new messages