Returning distinct rows in SQLAlchemy with SQLite

后端 未结 2 1580
面向向阳花
面向向阳花 2020-12-10 00:17

SQLAlchemy\'s Query.distinct method is behaving inconsistently:

>>> [tag.name for tag in session.query(Tag).all()]
[u\'Male\', u\'Male\', u\'Ninja\'         


        
2条回答
  •  余生分开走
    2020-12-10 00:52

    When you use session.query(Tag) you alway query for the whole Tag object, so if your table contains other columns it won't work.

    Let's assume there is an id column, then the query

    sess.query(Tag).distinct(Tag.name)
    

    will produce:

    SELECT DISTINCT tag.id AS tag_id, tag.name AS tag_name FROM tag
    

    The argument to the distinct clause is ignored completely.

    If you really only want the distinct names from the table, you must explicitly select only the names:

    sess.query(Tag.name).distinct()
    

    produces:

    SELECT DISTINCT tag.name AS tag_name FROM tag
    

提交回复
热议问题