3

我正在尝试通过同一模型中的另一个 many2many 字段在保存模型时预先填充 many2many 字段:

class CommissionReport(models.Model):
   ...
   law = models.ManyToManyField('Law', blank=True, null=True)
   categories = models.ManyToManyField('LawCategory', blank=True, null=True)
   ...

Law 模型的类别字段是 Many2Many 到 LawCategory,我试图抓住它并将这些类别添加到 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 回答