简体   繁体   English

SQLAlchemy的; 将主键设置为预先存在的db表(不使用sqlite)

[英]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? sqlalchemy中是否有任何方法可以将主键设置为已存在的id列? (Ideally from the Users object shown below). (理想情况下,来自下面显示的Users对象)。

Btw, I'm using postgresql (vs sqlite which doesn't seem to allow setting a primary after a table has been created ). 顺便说一句,我正在使用postgresql (vs sqlite 似乎不允许在创建表后设置主要内容 )。


FYI 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). 我想通过user.first_name = "John"通常完成的给定行的属性(列)名称设置值(例如,通过user.first_name = "John"语法)。

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 : 您也可以更改基础表,从长远来看这是正确的做法,但如果users.id的值唯一标识一行, 您可以手动指示SQLAlchemy将其作为主键 明确地部分处理指定类映射

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. 使用原始DDL语句。 If the column id is already unique: 如果列id已经是唯一的:

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: 如果id列不唯一,则必须删除它并重新创建:

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. 在Postgres中,以这种方式添加列将自动在后续行中使用连续数字填充列。

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

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