Search code examples
pythonsqlsqlobject

How to translate this to SQLObject: SELECT DISTINCT columnname WHERE


I've been going through the sqlobject and sqlbuilder documentation and forums and I cannot seem to grasp the information there.

I have a specific SQL query that I need:

select distinct author from blogtable where keyword = "dust";

Multiple authors can post about multiple subjects.

The query works on the MySQL database if I use the raw sql query. But I can't seem to understand what I must do to get this correctly working in SQLObject.

I see heaps of references to sqlbuilder, but the manual page is not very extensive. The examples provided in the google groups also talk as if SQLbuilder is the answer, but again, no specific example (for my problem) that I can understand.

Could someone well versed in SQLObject explain to me how I implement the above SQL in SQLObject ? If not possible, can I pass the raw sql in any way via SQLObject to the underlying db ?


Solution

  • I don't have much experience with SQLObject, but from the docs I deduce that it should be something like this:

    class Blog(SQLObject):
        class sqlmeta:
            table = 'blogtable'
    
        author = StringCol()
        keyword = StringCol()
    
    Blog.select(Blog.q.keyword=='dust', distinct=True)
    

    Version 2

    select = Select(
        [Blog.q.author],
        Blog.q.keyword=='dust',
        distinct=True,
    )
    
    sql = connection.sqlrepr(select)
    
    for author in connection.queryAll(sql):
        print author