M
M
Michael2014-09-30 10:43:24
Django
Michael, 2014-09-30 10:43:24

How to correctly fill in Django ManyToMany field in post_save trigger?

Hello, I'm trying to populate a ManyToMany field in a post_save trigger. Approximate code looks like this:

@receiver(post_save, sender=Post, dispatch_uid='update_post_images')<br>
def update_post_images(sender, instance, using, **kwargs):<br>
   post_save.disconnect(update_post_images, sender=Post, dispatch_uid='update_post_images')<br>
   print 'before', instance.images.all()<br>
   img = Image.object.get(pk=1469)<br>
   instance.images.add(img)<br>
   print 'after', instance.images.all()<br>
   post_save.connect(update_post_images, sender=Post, dispatch_uid='update_post_images')<br>

Now I see everything in the server console as it should be.
print 'before', instance.images.all() - displays one image
print 'after', instance.images.all() - displays 2 (the old one and the one that was added) But after the trigger has worked ,
nothing changes because
e. in manage.py shell at the request Post.objects.get(pk=.....).images.all() - I still see the same ONE object (and in the admin panel too)
Please help me solve the problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2014-09-30
@1099511627776

here is the code that helped (found here: stackoverflow.com/questions/4432385/django-how-to-...

class MyModel(models.Model):

    m2mfield = ManyToManyField(OtherModel)

    @staticmethod
    def met(sender, instance, action, reverse, model, pk_set, **kwargs):
        if action == 'pre_add':
            # here you can modify things, for instance
            pk_set.intersection_update([1,2,3]) 
            # only save relations to objects 1, 2 and 3, ignoring the others
        elif action == 'post_add':
            print pk_set
            # should contain at most 1, 2 and 3

m2m_changed.connect(receiver=MyModel.met, sender=MyModel.m2mfield.through)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question