简体   繁体   中英

Python sqlalchemy mapping tables without primary key

I have a 3rd party database which I try to map with sqlalchemy and python. The table in the database does not use a primary key. And I like to avoid table definitions by myself because the table has a lot of columns. So I wrote the following code

Found the below mapper args in the documentation of sqlalchemy.

class MyTable(Base):
  __tablename__ = 'MyTable'
  __mapper_args__ = {'primary_key':[some_table_with_no_pk.c.uid, some_table_with_no_pk.c.bar]
.....
}

But to me its unclear how to add the correct naming, something like

{'primary_key':['MyTable', 'MyColumnInTable'] }
or
{'primary_key':'[MyTable, MyColumnInTable]' }

does not work. How do I map this? Thanks for any help

Found the correct syntax:

class Channel(Base):

   __tablename__ = 'MyTable'
   __table__ = Table(__tablename__, Base.metadata, autoload=True, autoload_with=Engine)   
   __mapper_args__ = {'primary_key': [__table__.c.MyColumnInTable]} 
... 
}

This worked for me.

Another solution would be: Overriding Reflected Columns (found also in sqlalchemy doku)

Column('MyColumnInTable', Integer, primary_key=True),   # override reflected 'id' to have primary key

Thanks

As you can read here :

primary_key – A list of Column objects which define the primary key to be used against this mapper's selectable unit. This is normally simply the primary key of the local_table, but can be overridden here.

So you can do it like this:

class MyTable(Base):
    __tablename__ = "my-table"

    field1 = Column(String(10))
    field2 = Column(String(10))

    __mapper_args__ = {
        "primary_key":[field1, field2]
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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