【发布时间】:2015-03-01 22:27:30
【问题描述】:
假设我有这些基本模型:
class Trackable(PolymorphicModel):
uuid = UUIDField(unique=True)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
子模型扩展了它:
class Like(Trackable):
content = models.ForeignKey(Content, related_name='likes')
class Meta:
unique_together = ['content', 'created_by']
当我运行迁移时,它抱怨:
django.db.models.fields.FieldDoesNotExist: Like has no field named u'created_by'
【问题讨论】:
-
您希望
Trackable成为自己的表,通过外键与Like相关联吗?如果没有,请使用abstract=True,您的unique_together将按预期工作。如果是这样,您将无法使用unique_together强制执行该约束。 -
我不确定使用 github.com/chrisglass/django_polymorphic 添加它是否能正常工作,因为我没有看到它提到在基本模型中使用 abstract=True。
-
我看了一眼那个项目,它看起来像是为
abstract=False继承而设计的。在这种情况下,您正在谈论两个不同的表,因此无法以这种方式使用unique_together。注意abstract=True会提供更好的性能并允许唯一约束,所以考虑一下你是否真的需要使用多个表。 -
感谢@KevinChristopherHenry 我需要使用多态模型,因为它会自动为我转换类型,而且多表允许我查询基本模型
标签: django django-models