I have a search bar which searches for users with the following query:
db.session.query(User).filter(or_(User.name.contains(keyword), User.location.contains(keyword))).limit(16).all()
As you can see, it searches using keywords (which comes from a list formed by the search query). If I search for 'John Smith', the search will find a user with a name containing 'John' and then the same user with a name containing 'Smith', so it will return the User twice.
To solve this issue I tried using distinct() like so:
db.session.query(User).distinct().filter(or_(User.name.contains(keyword), User.location.contains(keyword))).limit(16).all()
but it didn't work so I tried using distinct(User.id):
db.session.query(User).distinct(User.id).filter(or_(User.name.contains(keyword), User.location.contains(keyword))).limit(16).all()
though that did not work either. So what is the problem?
Edit:
One bit I forgot to mention the code looks like this:
query = 'John Smith'
for keyword in query.split():
db.session.query(User).distinct().filter(or_(User.name.contains(keyword), User.location.contains(keyword))).limit(16).all()
This is why it returns 2 of the same user. I use the for loop because there are other field to the database, so if I searched for John Smith Mexico it would search by each word.