博客五部曲之二 - 高级博客


1231 浏览 5 years, 3 months

12 Generic Foreign Key 2

版权声明: 转载请注明出处 http://www.codingsoho.com/

https://docs.djangoproject.com/en/1.11/ref/contrib/contenttypes/#generic-relations

有的时候它也叫做polymorphic,普通的ForeignKey只能指向某一个model,GenericForeignKey能够让你指向任何models。

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Comment(models.Model):
    # post = models.ForeignKey(Post)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

根据文档的指导修改如上,注销掉post ForeignKey,这个会包含在GenericForeignKey

因为model变了,所以数据库要重新migrate。GenericForeignKey在migrate会要求你填default值,这个比较复杂。我们可以重新生成comments的migration或者重新生成数据库。

删除database比较干净,对于刚开始开发阶段比较合适。

如果仅仅删除migration文件,重新生成新的文件,运行时会报错

no such column: comments_comment.content_type_id

我的解决方法是删除model及引用它的内容(后面会恢复回来),然后生成包含Remove/Delete的migrations。然后恢复model,重新生成新的。
还有一种方法是给ForeignKey和GenericForeignKey置成null=True,后面再恢复回来也能解决。

这样问题就能解决,重新打开admin,添加comments如下,这个就实现了和前面一样的功能。