简体   繁体   English

在post_save上添加M2M

[英]Adding M2M on post_save

I have an object that has a m2m relation, and I would like to populate it after saving. 我有一个具有m2m关系的对象,在保存后我想填充它。

The problem is that the signal is triggered, but the command add doesn't work. 问题是信号被触发,但是命令add不起作用。 I did try the same steps using python shell, and it worked fine. 我确实使用python shell尝试了相同的步骤,但效果很好。

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? 有什么提示吗?

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 如果要添加所有对象,则可以使用set()代替add ,可以查看文档-https://docs.djangoproject.com/zh_CN/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. 还有一个建议,如果您使用add则尝试在执行后立即打印instance.locations - instance.locations.add(*Locations.objects.all())并发布结果。

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/ https://timonweb.com/posts/many-to-many-field-save-method-and-the-django-admin/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM