我公司课程与自身有多种M2M关系
类公司(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")
我希望能够像这样动态添加M2M关系,但显然不起作用。有没有办法动态地做到这一点?
company, was_created = Company.objects.get_or_create(name=info)
setattr(self,key, company)
答案 0 :(得分:5)
知道了。只需要传递一个列表..
company, was_created = Company.objects.get_or_create(name=info)
setattr(self,key, [company,])
答案 1 :(得分:2)
语法用于添加M2M field.add(obj_pk or obj)
company, was_created = Company.objects.get_or_create(name=info)
self.comp.add(company)