本文介绍了post_save信号中没有ManyToManyField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

保存后,我需要处理Django模型中的数据,但是我还需要访问ManyToManyField.

I need to manipulate data from a Django model after its saving, but I also need to access the ManyToManyField.

这就是我想要做的:

class Lab(Model):
  institute = ManyToManyField(Institute)

def post_save_lab(sender, instance, created, *args, **kwargs):
  if not instance.institute.all():
    # Data processing...

post_save.connect(post_save_lab, sender=Lab)

问题是,instance.institute.all()那时总是空的……我怎么知道实验室是否成立?

The problem is, instance.institute.all() is always empty at that moment... How can I know if the lab has or has not institute?

我指定信号m2m_changed不能解决问题,因为如果ManyToMany关系中没有元素,则必须完成数据处理.因此,不会调用m2m_changed.

I specify that the signal m2m_changed doesn't solve the problem because my data processing must be done if there are NO elements in the ManyToMany relation. Therefor m2m_changed will not be called.

谢谢!

推荐答案

在保存模型实例之前,无法保存 m2m .如果您在发布后保存信号中创建对象 created == True 时正在寻找 m2m 实例,那么它将始终为空.

The m2m cannot be saved until model instance is saved. If you are looking for m2m instances when object is created created==True in post save signal then it will be always empty.

我认为您可以为 m2m_changed 信号.

I think you can have handler for m2m_changed signal.

这篇关于post_save信号中没有ManyToManyField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 04:56