在具有M2M关系的模型中。有没有办法在信号中获得这种关系领域的id?
class Foo(models.Model):
field1 = ...
bar = models.ManyToManyField(Bar)
@receiver(post_save/m2m_changed, sender=Foo)
def whatever(sender, instance, **kwargs):
# get the ID of bar instance here
我希望能够获取正在使用的Bar实例的id。有什么想法吗?
答案 0 :(得分:0)
[UPDATE]:
from django.db.models.signals import m2m_changed
def whatever(sender, instance, **kwargs):
print(kwargs['pk_set'])
m2m_changed.connect(whatever, sender=Foo.bar.through)
[老]:
instance.bar.values('id')
或instance.bar.values_list('id', flat=True)
答案 1 :(得分:0)
使用m2m_changed
@receiver(m2m_changed, sender=Foo)
def whatever(sender, instance, action, pk_set, **kwargs):
if action == "pre_add":
print pk_set
<强> pk_set 强>
对于pre_add,post_add,pre_remove和post_remove操作,这是一组已添加到关系中或从关系中删除的主键值。对于pre_clear和post_clear动作,这是None。
https://docs.djangoproject.com/en/1.10/ref/signals/#m2m-changed