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

时间:2022-06-02 14:38:21

Hey guys i have been tearing my hair with this problem for a whole day and i cant seem to find the way to fix it :/. So basically i`m trying to prepopulate many2many field on saving the model through another many2many field in the same model :

嘿伙计们,我一直在用这个问题撕裂我的头发一整天,我似乎无法找到解决问题的方法:/。所以基本上我试图通过同一模型中的另一个many2many字段预先填充many2many字段来保存模型:

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

The Law model has category field which is Many2Many to LawCategory and im trying to catch it and add those categories to the categories of the CommissionReport model. So im using signal and a method, here it is the code :

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)

It actually prints the correct categories but doesn`t add them or save them into the model.

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

Thanks in advance.

提前致谢。

1 个解决方案

#1


0  

Instead of fetching the report you can reuse the given instance. Like so:

您可以重用给定的实例,而不是获取报表。像这样:

@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)

#1


0  

Instead of fetching the report you can reuse the given instance. Like so:

您可以重用给定的实例,而不是获取报表。像这样:

@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)