1

I have an object that has a m2m relation, and I would like to populate it after saving.

The problem is that the signal is triggered, but the command add doesn't work. I did try the same steps using python shell, and it worked fine.

class Event(models.Model):
  name = models.CharField(max_lenght=40)
  location = models.ManyToManyField('Location')

class Location(models.Model):
   address = models.CharField(max_lenght=60)


@receiver(post_save, sender=Event)
def populate_location(sender, instance, **kwargs):
   instance.locations.add(*Locations.objects.all())

Any hint?

Stargazer
  • 1,442
  • 12
  • 19
  • Do you get any specific error message when you try to use the signal? – Johan Oct 01 '18 at 20:03
  • This looms a rather strange use case, since each time you save the `Event` (for example after updating the `name`), you will add all `Location`s to that `Event`? – Willem Van Onsem Oct 01 '18 at 20:04
  • @Johan no error at all. I got all values necessary inside the signal. If ai copy/past the same function inside the python shell, it works just fine. – Stargazer Oct 01 '18 at 20:56
  • @WillemVanOnsem I have some logic to deal if that. Just wanted the keep it clean here. – Stargazer Oct 01 '18 at 20:56
  • I see. I can't think of a solution at the moment, but it's possible to put that logic in the `save` function of the model instead of a signal. There you can also check if it's the first time the model is saved by checking `if self.pk is None: ...`. That approach would also keep the logic in one place. – Johan Oct 01 '18 at 20:59

2 Answers2

0

If you want to add all the objects you can use set() instead of add, you can have a look on documentation - https://docs.djangoproject.com/en/2.1/ref/models/relations/#django.db.models.fields.related.RelatedManager.set

One more suggestion, if you are using add then try to print instance.locations just after executing - instance.locations.add(*Locations.objects.all()) and post the result.

Pankaj Sharma
  • 2,185
  • 2
  • 24
  • 50
0

I have found the solution. I forgot to mention that I was trying to save from admin, and it seems that it was a crutial detail, sorry about this.

https://timonweb.com/posts/many-to-many-field-save-method-and-the-django-admin/

Stargazer
  • 1,442
  • 12
  • 19