简体   繁体   English

如何在SQLAlchemy中建模`UNIQUE`约束?

[英]How to model a `UNIQUE` constraint in SQLAlchemy?

I am writing a Flask/SQLAlchemy application in which I have users and groups. 我正在编写一个Flask / SQLAlchemy应用程序,其中包含用户和组。

Users can belong to several groups, and they have a unique number within each group . 用户可以属于多个组,并且每个组中都有唯一的编号 Asking about how to model the database I was advised to use the following table structure for my many-to-many relationship: 询问如何建模数据库我被建议使用以下表结构来实现我的多对多关系:

TABLE UserGroups
  GroupID 
  UserID
  UserNumber
  PRIMARY KEY (GroupID, UserID)
  UNIQUE (GroupID, UserNumber)
  FOREIGN KEY (GroupID)
    REFERENCES Groups (GroupID)
  FOREIGN KEY (UserID)
    REFERENCES Users (UserID)

Now I know how to create a regular many-to-many relationship with SQLAlchemy, but I don't know how to represent the UNIQUE constraint with the additional UserNumber field. 现在我知道如何使用SQLAlchemy创建常规的多对多关系,但我不知道如何用附加的UserNumber字段表示UNIQUE约束。

I don't have a lot of experience with database design, ORMs and SQLAlchemy, so this may be obvious, but I can't find a way to express it. 我没有很多数据库设计,ORM和SQLAlchemy的经验,所以这可能是显而易见的,但我找不到表达它的方法。

On of the things I don't get is: using a regular many-to-many relationship, my User class has a list-like attribute groups which contains all the groups he belongs to, but this completely hides the UserGroups joining-table and I don't know how to access the UserNumber field. 关于我没有得到的东西是:使用常规的多对多关系,我的User类有一个类似列表的属性groups ,其中包含他所属的所有组,但这完全隐藏了UserGroups -table和我不知道如何访问UserNumber字段。

This is all a bit blur to me. 这对我来说有点模糊。 Do you have any good example or explanations on how-to do such a thing with SQLAlchemy ? 你对SQLAlchemy如何做这样的事情有什么好的例子或解释吗?

The first part of the question (about creating a unique constraint with multiple columns) is already answered by cleg . 问题的第一部分(关于创建具有多列的唯一约束)已经由cleg回答

However, the default many-to-many approach doesn't work if you want to have additionally columns in the mapping table. 但是,如果要在映射表中另外添加列,则默认的多对多方法不起作用。 Instead, you should use the Association Object Pattern . 相反,您应该使用关联对象模式 Additionally, you can simplify the access between user and group with an association_proxy . 此外,您可以使用association_proxy简化用户和组之间的访问。

The proxied_association.py from the SQLAlchemy examples should be a good place to start. SQLAlchemy示例中proxied_association.py应该是一个很好的起点。

Use UniqueConstraint in your model. 在模型中使用UniqueConstraint In detailed it's described in this question: sqlalchemy unique across multiple columns 详细描述了这个问题: sqlalchemy在多个列中是唯一的

As for many-to-many relations, SQLAlchemy have pretty good tutorial . 对于多对多关系,SQLAlchemy有很好的教程

PS Sorry, I've missed with second part of answer (it's more complex then I've thought, so see answer from @schlamar), but first part is still correct. PS对不起,我错过了第二部分的回答(它比我想的更复杂,所以请看@schlamar的答案),但第一部分仍然是正确的。

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

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