sqlalchemy 複数の列にまたがる一意の質問

sqlalchemy 複数の列にまたがる一意の質問

場所を表すクラスがあるとします。場所は顧客に「属します」。場所は Unicode の 10 文字コードで識別されます。「場所コード」は、特定の顧客の場所間で一意である必要があります。

The two below fields in combination should be unique
customer_id = Column(Integer,ForeignKey('customers.customer_id')
location_code = Column(Unicode(10))

つまり、顧客「123」と顧客「456」の 2 人の顧客がいるとします。どちらも「main」という場所を持つことができますが、どちらも main という場所を 2 つ持つことはできません。

これをビジネス ロジックで処理することはできますが、sqlalchemy で要件を簡単に追加する方法がないことを確認したいと思います。unique=True オプションは、特定のフィールドに適用された場合にのみ機能するようで、これにより、テーブル全体ですべての場所に対して一意のコードのみを持つことになります。

ベストアンサー1

ドキュメントからの抜粋Column:

unique – True の場合、この列に一意制約が含まれていることを示します。また、indexも True の場合は、一意フラグを使用してインデックスを作成する必要があることを示します。制約/インデックスに複数の列を指定するか、明示的な名前を指定するには、UniqueConstraintまたはIndex構造を明示的に使用します。

これらはマップされたクラスではなくテーブルに属しているため、テーブル定義で宣言するか、次のように宣言型を使用する場合は、次のように宣言します__table_args__

# version1: table definition
mytable = Table('mytable', meta,
    # ...
    Column('customer_id', Integer, ForeignKey('customers.customer_id')),
    Column('location_code', Unicode(10)),

    UniqueConstraint('customer_id', 'location_code', name='uix_1')
    )
# or the index, which will ensure uniqueness as well
Index('myindex', mytable.c.customer_id, mytable.c.location_code, unique=True)


# version2: declarative
class Location(Base):
    __tablename__ = 'locations'
    id = Column(Integer, primary_key = True)
    customer_id = Column(Integer, ForeignKey('customers.customer_id'), nullable=False)
    location_code = Column(Unicode(10), nullable=False)
    __table_args__ = (UniqueConstraint('customer_id', 'location_code', name='_customer_location_uc'),
                     )

おすすめ記事