如何在两个字段上添加独特的约束

发布于 2025-02-06 10:10:30 字数 306 浏览 3 评论 0 原文

我使用ponyorm,我想在两个字段的组合中添加独特的约束。

这是一个示例(ponyeditor链接:)。

我有两个表格,父母 child 。父母可以有很多孩子,但没有两个孩子。这意味着我想对子表的夫妇(父母,名称)添加独特的约束。

这很简单,但是我不知道python语法要做。

I use PonyORM, and I want to add a unique constraint on a combination of two fields.

Here's an example (PonyEditor link : https://editor.ponyorm.com/user/lial_slasher/DoubleConstraint).

I have two tables, Parent and Child. A parent can have many childs, but not two with the same name. Which means I want to add a unique constraint on the couple (parent, name) of the Child table.

It's pretty straightforward, but I can't figure out the python syntax to do it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

停滞 2025-02-13 10:10:30

您可以使用 Composite_key ,根据文档,在SQL中的几列上等同于 unique

示例:

from pony.orm import *
db = Database()

class Parent(db.Entity):
    name = Required(str)
    children = Set("Child")

class Child(db.Entity):
    parent = Required(Parent)
    name = Required(str)
    composite_key(parent_id, name)

在这里, name Child 类中的属性将与 parent 一起唯一具体名称。这等于以下SQL查询:

CREATE TABLE IF NOT EXISTS public.child
(
    id integer NOT NULL DEFAULT nextval('child_id_seq'::regclass),
    parent integer NOT NULL,
    name text COLLATE pg_catalog."default" NOT NULL,
    CONSTRAINT child_pkey PRIMARY KEY (id),
    CONSTRAINT unq_child__name_parent UNIQUE (name, parent),
    CONSTRAINT fk_child__parent FOREIGN KEY (parent)
        REFERENCES public.parent (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE
)

You can use composite_key which according to the document, is equivalent to UNIQUE on several columns in SQL.

example:

from pony.orm import *
db = Database()

class Parent(db.Entity):
    name = Required(str)
    children = Set("Child")

class Child(db.Entity):
    parent = Required(Parent)
    name = Required(str)
    composite_key(parent_id, name)

Here, the name attribute in the Child class will be unique together with the parent which means each parent can have exactly one child with a specific name. This is equal to the following SQL query:

CREATE TABLE IF NOT EXISTS public.child
(
    id integer NOT NULL DEFAULT nextval('child_id_seq'::regclass),
    parent integer NOT NULL,
    name text COLLATE pg_catalog."default" NOT NULL,
    CONSTRAINT child_pkey PRIMARY KEY (id),
    CONSTRAINT unq_child__name_parent UNIQUE (name, parent),
    CONSTRAINT fk_child__parent FOREIGN KEY (parent)
        REFERENCES public.parent (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文