基于另一个M2M预先填充Django M2M字段

时间:2013-06-27 15:27:35

标签: python django django-admin m2m

嘿伙计们,我一直在用这个问题撕裂我的头发一整天,我似乎无法找到解决问题的方法:/。所以基本上我试图通过同一模型中的另一个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)

它实际上会打印正确的类别,但不会添加它们或将它们保存到模型中。

提前致谢。

1 个答案:

答案 0 :(得分: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)