我在models.py
class Page(models.Model)
#fields
class News(Page)
#no fields
class NewsComment(models.Model)
news = models.Foreignkey(news)
name = models.CharField(max_length=128)
email = models.EmailField(max_length=75)
comment = models.TextField()
每次我尝试这个:
page = get_object_or_404(News, id=page_id)
然后
comment, created = NewsComment.objects.get_or_create(news=page, name=name, email=email, comment=text)
我收到此错误:
(1452, 'Cannot add or update a child row: a foreign key constraint fails (myproject_db.main_newscomment, CONSTRAINT news_id_refs_page_ptr_id_5a5b8a6204eece43 FOREIGN KEY (news_id) REFERENCES main_news (page_ptr_id))')
我做错了什么?
(PS:我正在使用带有InnoDB存储引擎的MySQL)
答案 0 :(得分:3)
如果新闻模型没有字段,则应使用a proxy model实现继承。它将导致更简单的数据库模式,以及更简单和更快速(!)的查询。它还将消除大多数问题,这些问题涉及如何在数据库级别上实现模型继承。
class Page(models.Model)
#fields
class News(Page)
class Meta:
proxy = True