简体   繁体   中英

Sqlalchemy; setting a primary key to a pre-existing db table (not using sqlite)

I have pre-existing tables in a database that I would like to use the automap pattern on.

However, to be able to use this pattern you need to have primary keys set as shown in the docs (and tried myself; failed like this ).

Is there any way in sqlalchemy to set a primary key to an already existing id column? (Ideally from the Users object shown below).

Btw, I'm using postgresql (vs sqlite which doesn't seem to allow setting a primary after a table has been created ).


FYI

So far I have been able to successfully access data as follows:

from sqlalchemy import Table, MetaData
from sqlalchemy.orm import sessionmaker

metadata = MetaData(engine)
Users = Table('users', metadata, autoload=True)  

Session = sessionmaker(bind=engine)
session = Session()
user_q = session.query(Users).filter(Users.c.id==1)

But this gives me a list where I need to access values with indexes. I want to set values by attribute (column) names for a given row like done typically in sqlalchemy (eg via a user.first_name = "John" syntax).

You could alter the underlying table as well and it would be the right thing to do in the long run, but if the values in users.id uniquely identify a row, you can manually instruct SQLAlchemy to treat it as a primary key by explicitly partially specifying the class mapping :

Base = automap_base()

class Users(Base)
    __tablename__ = 'users'
    # Override id column, the type must match. Automap handles the rest.
    id = Column(Integer, primary_key=True)    

# Continue with the automapping. Will fill in the rest.
Base.prepare(engine, reflect=True)

Use a raw DDL statement. If the column id is already unique:

con = sqlalchemy.create_engine(url, client_encoding='utf8')
con.execute('alter table my_table add primary key(id)')

If id column is not unique, you have to drop it and recreate:

con.execute('alter table my_table drop id')
con.execute('alter table my_table add id serial primary key')

In Postgres adding a column in this way will automatically populate the column with consecutive numbers in subsequent rows.

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