简体   繁体   English

使用多个表中的数据的唯一约束(SQL / SQLAlchemy)

[英]Unique constraint using data in multiple tables (SQL / SQLAlchemy)

A top class called Parametric is used to create objects which can have parameters associated with them:一个名为Parametric的顶级类用于创建可以具有与其关联的参数的对象:

class Parametric(object):
 def __init__(self, name):
  self.name = name
  self.pars = []

class Foo(Parametric):
 def __init__(self, name, prop):
  self.prop = prop
  Parametric.__init__(self, name)

class Bar(Parametric):
 def __init__(self, name, prop):
  self.prop = prop
  Parametric.__init__(self, name)

I use SQLAlchemy for my ORM engine.我的 ORM 引擎使用 SQLAlchemy。

I want to impose a UNIQUE constraint that ensures that the combination ( name , prop ) are unique for a given class (eg only one instance of Foo can be called "my_foo" and have a prop value of, say "my_prop" ), but I don't see how to reference the name column from Parametric in the Foo table UNIQUECONSTRAINT section.我想施加一个UNIQUE约束,以确保组合( nameprop )对于给定的类是唯一的(例如,只有一个Foo实例可以称为"my_foo"并且具有一个prop值,比如"my_prop" ),但是我没有看到如何在FooUNIQUECONSTRAINT部分中从Parametric引用name列。

Is this uniqueness something which can be imposed via FOREIGN KEY directives?这种独特性是否可以通过FOREIGN KEY指令强加?

You could do this using single table inheritance . 您可以使用单表继承来执行此操作。 However if your two columns are in different tables, you can't do exactly what you're trying to do (it is not possible to do a unique constraint across tables). 但是,如果您的两列位于不同的表中,则无法完全执行您要尝试执行的操作(不可能在表之间进行唯一约束)。

If single table inheritance is not an option, you probably want to either (1) enforce uniqueness in python, or (2) abandon sqlalchemy inheritance, and just use a foreign key to link Foo and Bar to Parametric. 如果不能选择单表继承,则可能要(1)在python中强制执行唯一性,或者(2)放弃sqlalchemy继承,而只需使用外键将Foo和Bar链接到Parametric。 You could foreign key to name , and THEN do a unique constraint on name and prop . 你可以外键name ,然后做一个唯一约束nameprop

如果有 2 个不同的表,您可以在表单验证中检查它是否重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM