开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜