Thomas Morrison
Thomas Morrison

Reputation: 647

Using SQLalchemy distinct function on Flask DB class

Is it possible to use the distinct function with out using the "session" class in sqlalchemy? Why or why not? The answer I found here:https://stackoverflow.com/a/35718413/10210394 seems like it should work but it doesn't work for me. See example below:

class Example(db.Model):
     title = db.Column(db.String(140))
     extra = db.Column(db.String(140))

e1 = Example(title='foo', extra='bar')
e2 = Example(title='hoo', extra='bar')

db.session.add_all([e1, e2])
db.session.commit()

test = []
for value in Example.query.distinct(Example.extra):
    test.append(value.extra)

print(len(test))
...2

The result should be 1 not 2. Looking at the docs for distinct(), I feel like this should work. What am I missing?

Upvotes: 2

Views: 3211

Answers (1)

Thomas Morrison
Thomas Morrison

Reputation: 647

I found several ways to accomplish what I wanted. Looking at this answer https://stackoverflow.com/a/17224056/10210394, in order to get the distinct values distinct() has to be called explicitly on the values. To do this in the class form one can use "with_entities"

Example.query.with_entities(Example.extra).distinct()

Also, in my case, a simple group_by also achieves the desired results(but it may not be the best/most portable solution as pointed out in the comments.)

 test = []
    for value in Example.query.group_by(Example.extra):
        test.append(value.extra)

 print (test)
 ....['bar']

Upvotes: 6

Related Questions