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)
Got it. Simply have to pass a list instead..
company, was_created = Company.objects.get_or_create(name=info)
setattr(self,key, [company,])
The syntax is for adding M2M is field.add(obj_pk or obj)
company, was_created = Company.objects.get_or_create(name=info)
self.comp.add(company)
精彩评论