我有以下信号:
@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 对象。
此类信号已经可以工作双向。所以无论你如何添加元素。
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