我对 django 有一个问题,我真的无法理解。坚持了两天,一直在寻找源代码,但我找不到任何解释,希望有人比我更了解这一点!
我有两个模型,Publication就像Article这样
class Publication(models.Model):
title = models.CharField(max_length=30)
articles = models.ManyToManyField('Article',blank=True)
class Meta:
db_table = 'publications'
class Article(models.Model):
headline = models.CharField(max_length=100)
class Meta:
db_table = 'articles'
当我保存新文章时Publication,我想自动保存默认文章。我做了一个脚本来测试它,它工作正常。两个对象都在各自的表中创建,并且将一个条目写入publications_articles表中。正如预期的那样。
publication = Publication(title='The new exciting publication')
publication.save()
publication.articles.create(headline='The article that makes the pub so exciting')
然而,这是棘手的部分。为了在管理员中保存 a 时具有相同的功能,Publication我确实覆盖了save_model()这样的功能。
class PublicationAdmin(admin.ModelAdmin):
list_display = ['title']
def save_model(self, request, obj, form, change):
if not change:
obj.save()
obj.articles.create(headline='The article that makes this pub so exciting')
else:
obj.save()
Publication在管理员中保存 a会同时创建 thePublication和 theArticle但publications_articles表中没有将它们绑定在一起的条目!
有人请,请解释这种行为。我即将做一个原始的 sql-insert 只是为了完成它,但我想了解为什么实体之间没有建立连接。