【问题标题】:Prepopulating Django M2M field based on another M2M基于另一个 M2M 预填充 Django M2M 字段
【发布时间】:2013-06-25 04:42:02
【问题描述】:

我正在尝试通过同一模型中的另一个 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)

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

提前致谢。

【问题讨论】:

  • category 的类型是 LawCategory 吗?
  • 是的“类别”是与法律相关的 LawCategory 之一 :)

标签: python django django-admin m2m


【解决方案1】:

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

@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-02-05
  • 2021-03-16
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
相关资源
最近更新 更多