簡體   English   中英

如何在SQLAlchemy中定義復合主鍵

[英]How to define composite primary key in SQLAlchemy

我正在嘗試使用SQLAlchemy和MySQL為具有復合主鍵的表創建表映射,我不確定我是否正確行事。 使用復合主鍵定義現有表。

這是映射類定義:

class table1(Base):
    __tablename__ = 'table1'

    col1 = Column(String, primary_key=True)
    col2 = Column(String, primary_key=True)
    col3 = Column(String)

    def __init__ = (self, col1, col2, col3):
        self.col1 = col1
        self.col2 = col2
        self.col3 = col3

這匹配數據庫中已有的記錄a = table1('test','test','test')

如果我將此添加到會話並在表中添加記錄,然后使用數據,我得到MySQL錯誤(1062重復條目)。

session.add(a)
b = session.query(table1)
for instance in b:
    print(instance.col1, instance.col2)

如果我正在使用單鍵表,我會收到此錯誤:

New instance <table2 at 0x2f204d0> with identity key 
(<class '__main__.table2'>,('test',)) conflicts with 
persistent instance <table2 at 0x2f88770>

我是否錯誤地定義了復合主鍵? 如果沒有,我為什么要進一步錯誤地得到MySQL錯誤而不是Python / SQLAlchemy錯誤?

我同意這個問題含糊不清。 但您可以使用以下內容作為指導。 這將從MySQL中的test數據庫中的trial1表中進行選擇。 注釋掉的部分作為設置主鍵約束的替代方法。

from sqlalchemy import String, create_engine, MetaData, Column
from sqlalchemy.ext.declarative import declarative_base
# from sqlalchemy.schema import PrimaryKeyConstraint
from sqlalchemy.orm import sessionmaker

engine = create_engine('mysql+pymysql://root:root@127.0.0.1/test')
metadata = MetaData(bind=engine)
Base = declarative_base(metadata=metadata)


class TableClassName(Base):
    __tablename__ = 'table1'

    col1 = Column(String, primary_key=True)
    col2 = Column(String, primary_key=True)
    col3 = Column(String)

    # __table_args__ = (
    #     PrimaryKeyConstraint(
    #         col1,
    #         col2),
    #     {})

Session = sessionmaker(bind=engine)
session = Session()

b = session.query(TableClassName)
for instance in b:
   print(instance.col1, instance.col2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM