Prefilling a Django M2M Field Based on Another M2M

Hey guys, I've been tearing my hair off this problem all day, and I can't find a way to fix it: /. Thus, basically I am trying to sprinkle many many fields to save the model through another many fields in the same model:

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

In the law model, there is a category field, which is a lot of for the LawCategory, and I'm trying to catch it and add these categories to the categories of the CommissionReport model. So I use the signal and method, here is the code:

 @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 does print the correct categories, but does not add them or save them in the model.

Thanks in advance.

+4
source share
1 answer

Instead of receiving a report, you can reuse this instance. For instance:

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

Source: https://habr.com/ru/post/1488522/


All Articles