反向时的m2m_changed实例

问题描述 投票:0回答:1

我有以下信号:

@receiver(m2m_changed, sender=User.cars.through)
def car_added_to_user(sender, instance, action, **kwargs):
    if action in ("post_add",):
        cache.delete(f"user-{instance.pk}")

我可以在执行时按预期触发它:

User.cars.add(car)

但是如果我也想在这种情况下从缓存中删除用户,我该怎么办?

Car.user_set.add(user)

在本例中,实例是 Car 对象,而不是 User 对象。

django django-models django-signals
1个回答
0
投票

此类信号已经可以工作双向。所以无论你如何添加元素。

事实上,这是

m2m_changed
信号 signal [Django-doc] 的警告之一:
sender
instance
可以是
User
Car
,但是还有一个
Car
User
,因此使写入信号变得更加复杂。

@receiver(m2m_changed, sender=User.cars.through)
def car_added_to_user(sender, instance, action, **kwargs):
    if action == 'post_add':
        if isinstance(sender, User):
            # did through my_user.cars.add(my_car)
            cache.delete(f"user-{instance.pk}")
            # my_user is the sender
            # my_car is the instance
        elif isinstance(sender, Car):
            # did through my_car.user_set.add(my_user)
            # my_car is the sender
            # my_user is the instance
            pass
© www.soinside.com 2019 - 2024. All rights reserved.