Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add ManyToMany relationship to Django objects

My Company class have multiple M2M relationship 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 relationship like this, but it obviously does not work. Is there a way to do it dynamically ?

                    company, was_created = Company.objects.get_or_create(name=info)
                    setattr(self,key, company)
like image 582
philgo20 Avatar asked Feb 25 '23 08:02

philgo20


1 Answers

Got it. Simply have to pass a list instead..

 company, was_created = Company.objects.get_or_create(name=info)
                        setattr(self,key, [company,])
like image 120
philgo20 Avatar answered Apr 28 '23 19:04

philgo20