从m2m实例获取ID

时间:2017-03-10 09:06:39

标签: django django-models

在具有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。有什么想法吗?

2 个答案:

答案 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

相关问题
最新问题