要使用的信号不是post_save,而是m2m_changed,它是在模型保存到数据库后发送的。
@models.signals.m2m_changed(sender=MyModel.second_m2m.through)
def duplicate_other_on_this_if_empty(sender, instance, action, reverse, model, pk_set, **kwargs):
# just before adding a possibly empty set in "second_m2m", check and populate.
if action == 'pre_add' and not pk_set:
instance.__was_empty = True
pk_set.update(instance.first_m2m.values_list('pk', flat=True))
@models.signals.m2m_changed(sender=MyModel.first_m2m.through)
def duplicate_this_on_other_if_empty(sender, instance, action, reverse, model, pk_set, **kwargs):
# Just in case the "first_m2m" signals are sent after the other
# so the actual "population" of the "second_m2m" is wrong:
if action == 'post_add' and not pk_set and getattr(instance, '__was_empty'):
instance.second_m2m = list(pk_set)
delattr(instance, '__was_empty')
编辑:下一个代码更简单,并且基于模型定义的新知识
在您的代码中,“first_m2m”信号在“second_m2m”之前发送(这实际上取决于您的模型定义)。所以我们可以假设当接收到“second_m2m”信号时,“first_m2m”已经填充了当前数据。
这让我们更开心,因为现在您只需要检查 m2m-pre-add:
@models.signals.m2m_changed(sender=MyModel.second_m2m.through)
def duplicate_other_on_this_if_empty(sender, instance, action, reverse, model, pk_set, **kwargs):
# just before adding a possibly empty set in "second_m2m", check and populate.
if action == 'pre_add' and not pk_set:
pk_set.update(instance.first_m2m.values_list('pk', flat=True))