同じモデルの別の many2many フィールドを介してモデルを保存する際に、many2many フィールドを事前設定しようとしています。
class CommissionReport(models.Model):
...
law = models.ManyToManyField('Law', blank=True, null=True)
categories = models.ManyToManyField('LawCategory', blank=True, null=True)
...
Law モデルには、LawCategory に対して Many2Many であるカテゴリ フィールドがあり、それをキャッチしてそれらのカテゴリを CommissionReport モデルのカテゴリに追加しようとしています。シグナルとメソッドを使用しているので、コードは次のとおりです。
@staticmethod
def met(sender, instance, action, reverse, model, pk_set, **kwargs):
if action == 'post_add':
report = CommissionReport.objects.get(pk=instance.pk)
if report.law:
for law in report.law.all():
for category in law.categories.all():
print category
report.categories.add(category)
report.save()
m2m_changed.connect(receiver=CommissionReport.met, sender=CommissionReport.law.through)
実際には正しいカテゴリを出力しますが、それらをモデルに追加したり保存したりしません。
前もって感謝します。