Django:GenericForeignKey和unique_together

Cyb*_*Fly 12 python django abstract-class

在我正在处理的应用程序中,我正在尝试在公司内共享访问令牌.示例:当地办事处可以使用总部的代币在其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
Run Code Online (Sandbox Code Playgroud)

由于Facebook,Twitter和其他社交媒体网站以自己的方式处理访问令牌,因此我制作了抽象类AccessToken.每个站点都有自己的类,例如

class FacebookAccessToken(AccessToken):
    # class stuff
Run Code Online (Sandbox Code Playgroud)

在做了一些阅读之后,我发现我必须使用a 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'))
Run Code Online (Sandbox Code Playgroud)

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

core.ShareAccessToken :( models.E016)'unique_together'指的是字段'contentObject',它不是模型'ShareAccessToken'的本地.提示:此问题可能是由多表继承引起的.

我不明白为什么我第一次使用这个错误GenericForeignKey.我究竟做错了什么?

如果有一种更聪明的方式来分享访问令牌,我很乐意听到它.

Der*_*wok 17

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

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

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

unique_together = (('contentType', 'contentId', 'sharedWidth'),)
Run Code Online (Sandbox Code Playgroud)

这相当于你已经在你的问题中定义什么,因为contentObject实在是刚刚组合contentType,并contentId在幕后.

  • 我认为您的意思是“objectId”而不是“contentId”。 (4认同)