【发布时间】:2017-06-09 00:32:04
【问题描述】:
我有以下型号:
class Offering(models.Model):
entity = models.OneToOneField('companies.entity')
company_type = models.ManyToManyField(CompanyTypeChoice, blank=True)
@python_2_unicode_compatible
class Tag(models.Model):
word = models.CharField(max_length=64)
@python_2_unicode_compatible
class Entity(models.Model):
tags = models.ManyToManyField(Tag,related_name='companies', blank=True, null=True)
class CompanyTypeChoice(models.Model):
title = models.CharField(max_length=64)
我有以下循环,我想创建一个 M2M 标记关系:
offerings = Offering.objects.all()
for o in offerings:
for ct in o.company_type.all():
tag = Tag.objects.get(word=ct.title)
e = Entity.objects.get(pk=o.entity.id)
e.tags.add(tag)
这不会保存 M2M 关系。我做错了什么?
【问题讨论】:
-
Django 是否设置为自动提交?
CompanyTypeChoice模特也好吗? -
@BishwasMishra 。我没有更改自动提交的默认值。 CompanyType 有值并且正在循环。我也发布了 CompanyTypeChoice 模型。
标签: python django django-models many-to-many