简体   繁体   English

是否可以在 sqlalchemy 中同时使主键和外键唯一

[英]Is it possible to make a primary key and foriegn key unique together in sqlalchemy

I have my table like this and I want siteid and device as unique and also there must be a primary key to this table.我的表是这样的,我希望siteiddevice是唯一的,并且该表必须有一个主键。 So I assigned device as primary key.所以我将设备分配为主键。

class SiteRoleMapping(db.Model):
    __table_name__ = "site_role_mapping"
    siteid = Column(ForeignKey(('cmp_site.id'), ondelete='CASCADE'), nullable=False)
    device = Column(String, primary_key=True)
    rolename = Column(String)
    description = Column(String, default="None")

Without knowing much about your database, I think you should just give the mapping an Integer Primary Key and add a unique constraint on the two fields you want to have unique.在不太了解你的数据库的情况下,我认为你应该给映射一个整数主键,并在你想要唯一的两个字段上添加一个唯一约束。

Like this:像这样:

from sqlalchemy import UniqueConstraint

class SiteRoleMapping(db.Model):
    __table_name__ = "site_role_mapping"
    id = Column(Integer, primary_key)
    site_id = Column(ForeignKey('cmp_site.id', ondelete='CASCADE'), nullable=False)
    device = Column(String, primary_key=True)
    rolename = Column(String)
    description = Column(String, default="None")

    # add unique constraint
    __table_args__ = (UniqueConstraint('site_id', 'device'), )

However, reading the table name mapping, it sounds like you are implementing a many-to-many relationship between sites and roles.但是,阅读表名映射,听起来您正在实现站点和角色之间的多对多关系。 This is usually done using three tables, one for sites, one for roles and one for the mapping这通常使用三张表来完成,一张用于站点,一张用于角色,一张用于映射

So I would expect a mapping to have two foreign keys, not just one.所以我希望映射有两个外键,而不仅仅是一个。

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

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