3

I am trying to prepopulate many2many field on saving the model through another many2many field in the same model:

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 :

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

peterh
  • 11,875
  • 18
  • 85
  • 108
Iliyan Tatarov
  • 504
  • 4
  • 9

1 Answers1

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)
Alp
  • 29,274
  • 27
  • 120
  • 198
  • 1
    Thank you for your response, but this was the very first thing that i have tried and for unexplained reason it doesnt work, after saving the categories field is still empty. The console prints in the last loop the right categories and no errors are given. – Iliyan Tatarov Jun 28 '13 at 07:43
  • do you have transactions enabled and maybe another query which produces an error? that could cause a rollback – Alp Jun 28 '13 at 10:32