在我正在开发的应用程序中,我试图在公司内部共享访问令牌。例如:当地办事处可以使用总部的代币在他们的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
时会出现这个错误。我做错什么了?在
如果有一个更聪明的方法来分享访问令牌,我很乐意听到。在
在这种情况下使用通用外键是正确的。在
错误来自模型中的
unique_together
声明。unique_together
只能与数据库中存在的列一起使用。由于contentObject
不是一个真正的列,Django抱怨这个约束。在相反,您可以执行以下操作:
这与您在问题中所定义的相同,因为}在幕后的组合。在
contentObject
实际上只是contentType
和{相关问题 更多 >
编程相关推荐