drnextgis
drnextgis

Reputation: 2224

SQLAlchemy select only one column

Try to select one column from pg_shadow table the following way:

role_tbl = Table('pg_shadow', MetaData(engine), autoload=True)
db.query(role_tbl.c.passwd).filter_by(usename='name')

And get an error:

* AttributeError: 'NoneType' object has no attribute 'class_'

Upvotes: 2

Views: 5948

Answers (3)

Paul Rougieux
Paul Rougieux

Reputation: 11429

To select only one column you can use Select.with_only_columns:

from sqlalchemy import MetaData, Table, Column, Text
meta = MetaData()
table = Table('user', meta,
              Column("name", Text),
              Column("full_name", Text))
stmt = (table.select()
        .with_only_columns([table.c.name])
       )
print(stmt)

# SELECT "user".name
# FROM "user"

Upvotes: 0

Ilja Everilä
Ilja Everilä

Reputation: 53017

The error is the result of having no entity in the query:

The keyword expressions are extracted from the primary entity of the query, or the last entity that was the target of a call to Query.join().

where an entity is a mapped class, or the Table object, but you're querying a single column. The proper way to filter would be:

db.query(role_tbl.c.passwd).filter(role_tbl.c.usename == 'name')

In a more recent version of SQLAlchemy the error is:

NoInspectionAvailable: No inspection system is available for object of type <class 'NoneType'>

Upvotes: 2

Boris Pavlovic
Boris Pavlovic

Reputation: 1287

Try this one:

role_tbl.select([role_tbl.c.passwd]).where(username=='name').execute().fetchall()

Or probably there is no such column in this table.

You can check it by printing all columns

print role_tbl.columns

P.S. And also you should use one instance of metadata: MetaData(engine) (it should store information about all tables)

Upvotes: 0

Related Questions