Dynamically add ManyToMany relation to Django objects

My company class has several M2M relationships with itself.

class Company (models.Model):

divisions = models.ManyToManyField('self', symmetrical=False, related_name="parent_companies") parents = models.ManyToManyField('self', symmetrical=False, related_name="divisions_companies") comp = models.ManyToManyField('self', symmetrical=False, related_name="comp") friends = models.ManyToManyField('self', symmetrical=False, related_name="friends") 

I would like to be able to dynamically add M2M relationships like this, but this clearly doesn't work. Is there a way to do this dynamically?

  company, was_created = Company.objects.get_or_create(name=info) setattr(self,key, company) 
+4
source share
3 answers

Got it. You just need to pass the list instead.

  company, was_created = Company.objects.get_or_create(name=info) setattr(self,key, [company,]) 
+5
source

The syntax for adding M2M is field.add(obj_pk or obj)

 company, was_created = Company.objects.get_or_create(name=info) self.comp.add(company) 
+2
source

First, let me say thanks to OP for clarifying that the value must be list for such use.

I was not able to get the approach described in the accepted answer to work in my application, which used a slightly different approach, adding M2M relationships to non-owning objects.

I had to do this, which admittedly seems a bit hacky:

 setattr(target_object, f'{key}.all()', [source_object.__getattribute__(key), ]) 

Note the use of f'{key}.all()'

Without this, I get an error when I try to access ManyToManyField from the wrong side, which suggests using the field.set () method.

Probably not optimal, but hopefully useful for the next guy.

0
source

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


All Articles