Sqlalchemy Using Load_only With Distinct
Solution 1:
Deferring the primary key would not make sense, if querying complete ORM entities, because an entity must have an identity so that a unique row can be identified in the database table. So the query includes the primary key though you have your load_only()
. If you want the data only, you should query for that specifically:
In [12]: session.query(my_class.data).distinct().all()
2017-06-3012:31:49,200 INFO sqlalchemy.engine.base.Engine SELECTDISTINCT my_table.data AS my_table_data
FROM my_table
2017-06-3012:31:49,200 INFO sqlalchemy.engine.base.Engine ()
Out[12]: [(55)]
There actually was an issue where having load_only()
did remove the primary key from the select list, and it was fixed in 0.9.5:
[orm][bug] Modified the behavior of
orm.load_only()
such that primary key columns are always added to the list of columns to be “undeferred”; otherwise, the ORM can’t load the row’s identity. Apparently, one can defer the mapped primary keys and the ORM will fail, that hasn’t been changed. But as load_only is essentially saying “defer all but X”, it’s more critical that PK cols not be part of this deferral.
Post a Comment for "Sqlalchemy Using Load_only With Distinct"