gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:08:34 25 4
gpt4 key购买 nike

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

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

提前致谢。

最佳答案

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

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

关于python - 基于另一个 M2M 预填充 Django M2M 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17347238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com