字段,在外键中指定两次
问题描述:
我有以下模型。字段,在外键中指定两次
class Comment(models.Model):
type = models.CharField(max_length=21, choices=OBJECT_TYPE_CHOICES)
program = models.ForeignKey(Program, db_column='object_id', to_field='id', null=True, blank=True)
article = models.ForeignKey(Article, db_column='object_id', to_field='id', null=True, blank=True)
类型字段确定哪个字段(程序或文章)将处于活动状态。但是,当我尝试使用Django管理面板添加注释时,出现错误:"Column 'object_id' specified twice".
我明白为什么会出现此错误,但不明白如何解决此问题。
答
这种类型的行为不Django支持。即使你设法完成它,这是一个肮脏,肮脏的黑客攻击,并会导致任何开发人员对你的诅咒,任何应该永远不会继承你的代码。
使用contenttypes框架,特别是GenericForeignKeys:https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations
答
的问题是因为你使用相同的名称在数据库中的两个专栏中,我认为你应该使用这样的:
https://docs.djangoproject.com/en/1.3/ref/contrib/contenttypes/