当我在sqlall for a models.py中查看包含独特的_-together语句时,我没有注意到任何看起来像是强制执行的东西。
在我看来,我可以想象这些知识可能有助于数据库优化查询,例如:
“我已经找到一行spam 42和eggs 91,因此在搜索eggs 91时,不再需要检查spam 42的行。”
我说的这些知识对数据库有帮助是对的吗?
我说的对吗,它不是这样强制的(即,它只是由ORM强制的)?
如果两者都是,这是一个缺陷吗?
最佳答案
下面是一个例子。假设您有模型:
class UserConnectionRequest(models.Model):
sender = models.ForeignKey(UserProfile, related_name='sent_requests')
recipient = models.ForeignKey(UserProfile, related_name='received_requests')
connection_type = models.PositiveIntegerField(verbose_name=_(u'Connection type'), \
choices=UserConnectionType.choices())
class Meta:
unique_together = (("sender", "recipient", "connection_type"),)
运行sqlall返回:
CREATE TABLE "users_userconnectionrequest" (
"id" serial NOT NULL PRIMARY KEY,
"sender_id" integer NOT NULL REFERENCES "users_userprofile" ("id") DEFERRABLE INITIALLY DEFERRED,
"recipient_id" integer NOT NULL REFERENCES "users_userprofile" ("id") DEFERRABLE INITIALLY DEFERRED,
"connection_type" integer,
UNIQUE ("sender_id", "recipient_id", "connection_type")
)
当此模型在数据库上正确同步时,它具有唯一约束(postgres):
约束用户用户连接请求发送方id
唯一(发件人id、收件人id、连接类型),