gpt4 book ai didi

postgres : enforced by ORM or DB? 上的 Django unique_together

转载 作者:行者123 更新时间:2023-11-29 11:34:42 31 4
gpt4 key购买 nike

当我查看包含 unique_together 语句的 models.py 的 sqlall 时,我没有注意到任何看起来像执行的东西。

在我看来,我可以想象这些知识可能会帮助数据库优化查询,如下所示:

“我已经找到包含垃圾邮件 42 和鸡蛋 91 的行,因此在搜索鸡蛋 91 时,我不再需要检查包含垃圾邮件 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):

CONSTRAINT users_userconnectionrequest_sender_id_2eec26867fa22bfa_uniq UNIQUE (sender_id, recipient_id, connection_type),

关于postgres : enforced by ORM or DB? 上的 Django unique_together,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6643732/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com