3

同じモデルの別の 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)

実際には正しいカテゴリを出力しますが、それらをモデルに追加したり保存したりしません。

前もって感謝します。

4

1 に答える 1

0

レポートをフェッチする代わりに、特定のインスタンスを再利用できます。そのようです:

@staticmethod
def met(sender, instance, action, reverse, model, pk_set, **kwargs):

      if action == 'post_add':
           if instance.law:
               for law in instance.law.all():
                   for category in law.categories.all():
                       instance.categories.add(category)

           instance.save()

m2m_changed.connect(receiver=CommissionReport.met, sender=CommissionReport.law.through)
于 2013-06-28T00:24:44.900 に答える