简体   繁体   中英

How can I query over a table without primary key in sqlalchemy?

I need to get data from a table without primary key. I did the following to make it visible/mappable, however I still can't query through it. This is my code:

table = 'my_table'
db_tables = automap_base()
metadata = MetaData()
my_table = Table(table, db_tables.metadata, Column('row_id', Integer, primary_key=True), autoload=True, autoload_with=db.engine)
db_tables.prepare(db.engine, reflect=True)

#
data = db.session.query(db_tables.classes.my_table).filter(
    db_tables.classes.my_table.device_name.like('%uni%'),
)

The code crashes when I do the following:

Notice '.all()'

db.session.query(db_tables.classes.my_table).filter(
        db_tables.classes.my_table.device_name.like('%uni%'),
    ).all()

Or

data.all()

Or

for row in data:
  row.name

This is the error I get:

{ProgrammingError}(pyodbc.ProgrammingError) ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'row_id'. (207) (SQLExecDirectW)")

SQLAlchemy (and all ORMs that I have used) needs a primary key to operate.

That primary key however doesn't need to be set as primary key in the database, you can define it on a reflected table as a single column if you have a natural key, or a group of columns if you don't (up to using the full row as primary key).

You're setting row_id as your primary key, does it exist in the table ?

If not, you need to set another primary on existing columns.

http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key

When querying MYSQL using SA you can simply do:

session_object.query(Mapped_Tabale_Class_Name).filter_by(column_name="something").all()

Then iterate over the results if any and choose what you were looking for. For querying data you do not need to know the primary key, SA is supposed to take care of that for you

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