字段,在外键中指定两次

时间:2011-11-16 20:59:09

标签: django django-models django-orm

我有以下型号。

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".我理解为什么会出现此错误,但不明白如何修复它。

2 个答案:

答案 0 :(得分:2)

Django不支持此类行为。即使你设法完成它,它也是一个肮脏,肮脏的黑客,并且会导致任何开发人员诅咒你,这应该是非常不幸的继承你的代码。

使用contenttypes框架,特别是GenericForeignKeys:https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations

答案 1 :(得分:1)

问题是因为你在数据库中为两列使用相同的名称,我认为你应该使用它:

https://docs.djangoproject.com/en/1.3/ref/contrib/contenttypes/