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-事前加算をチェックする必要があるため
これは、私たちが幸せになります:
@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))
...オブジェクトを保存し、第二M2Mから関連データを取得し、最初のM2Mに設定して、もう一度それを保存します。 instance.save()ラインを押し、「s」は関数を入力し、で、何が起こっているかを確認するために直前pdb.set_trace()「N」あなたは次に行き。ここでは、[チュートリアル](http://pythonconquerstheuniverse.wordpress.com/category/python-debugger/)は念 – Hassek