Answer the question
In order to leave comments, you need to log in
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>
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question