我想从另一个模型中获取外键值并订阅它。
它在字段声明为ForeignKey
时有效,但当字段声明为ManyToManyField
时,它不起作用。
我该怎么办?
请帮忙。
class Document(models.Model):
project = models.ForeignKey(Project)
text = models.ForeignKey(Text, null=True, blank=True)
language = models.ManyToManyField(Language, null=True, blank=True)
def save(self, *args, **kwargs):
self.text = self.project.text #WORKS
self.language = self.project.language.all() #NOT WORKS
super(Document, self).save(*args, **kwargs)
答案 0 :(得分:0)
这样的事情有用吗?
class Document(models.Model):
project = models.ForeignKey(Project)
text = models.ForeignKey(Text, null=True, blank=True)
languages = models.ManyToManyField(Language) # no need to null/blank + put the name on plural if using a many to many relation.
def save(self, *args, **kwargs):
self.text = self.project.text
super(Document, self).save(*args, **kwargs)
# super() must be called BEFORE feeding your many to many.
project_languages = self.project.languages.all()
self.languages.add(*project_languages)
使用多对多字段属性时,您需要等待在多对多属性中添加值之前创建实例。
使用add
执行此操作,与外键字段相反。
答案 1 :(得分:0)
您需要使用.add()
初始化ManyToManyField
更改此行
# use plural naming convention when its ManyToMany relation `language` should be `languages` in your Document model
self.language = self.project.language.all()
到
# call save method of super class before adding values to many-to-many
super(Document, self).save(*args, **kwargs)
p_language = self.project.language.all()
self.language.add(*p_language)
因此,在添加多对多关系之前,您必须先调用save
。由于add会立即影响数据库,因此您无需事后保存。