Django:GenericForeignKey和unique_togeth

2024-09-30 18:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在我正在开发的应用程序中,我试图在公司内部共享访问令牌。例如:当地办事处可以使用总部的代币在他们的Facebook页面上发布内容。在

class AccessToken(models.Model):
    """Abstract class for Access tokens."""
    owner = models.ForeignKey('publish.Publisher')
    socialMediaChannel = models.IntegerField(
        choices=socialMediaChannelList, null=False, blank=False
    )
    lastUpdate = models.DateField(auto_now=True)

    class Meta:
        abstract = True

因为Facebook、Twitter和其他社交媒体网站处理访问令牌的方式都是我自己制作的抽象类AccessToken。每个站点都有自己的类

^{pr2}$

在阅读了一些之后,我发现我必须使用GenericForeignKey来指向继承AccessToken的类。我上了以下课程:

class ShareAccessToken(models.Model):
    """Share access tokens with other publishers."""
    sharedWith = models.ForeignKey('publish.Publisher')
    sharedBy = models.ForeignKey(User)

    # for foreignkey to abstract model's children
    contentType = models.ForeignKey(ContentType)
    objectId = models.PositiveIntegerField()
    contentObject = GenericForeignKey('contentType', 'objectId')

    class Meta:
        unique_together = (('contentObject', 'sharedWith'))

当我运行django测试服务器时,我得到以下错误:

core.ShareAccessToken: (models.E016) 'unique_together' refers to field 'contentObject' which is not local to model 'ShareAccessToken'. HINT: This issue may be caused by multi-table inheritance.

我不明白为什么第一次使用GenericForeignKey时会出现这个错误。我做错什么了?在

如果有一个更聪明的方法来分享访问令牌,我很乐意听到。在


Tags: tofalseformodelfacebookmodelspublishpublisher
1条回答
网友
1楼 · 发布于 2024-09-30 18:22:07

在这种情况下使用通用外键是正确的。在

错误来自模型中的unique_together声明。unique_together只能与数据库中存在的列一起使用。由于contentObject不是一个真正的列,Django抱怨这个约束。在

相反,您可以执行以下操作:

unique_together = (('contentType', 'contentId', 'sharedWidth'),)

这与您在问题中所定义的相同,因为contentObject实际上只是contentType和{}在幕后的组合。在

相关问题 更多 >