Question

user_exists = db.GqlQuery("select * from User where user_id in '%s'" % username)

I'm trying to do a test to see if a particular user id (user_id) already exists in the database(User). Basically, if 'user_exists' holds any results, I want to produce an error and re-render the form, and if it's empty, I want to continue on with storing a users data. How can I tell if 'user_exists' contains a result or not?

I have tried,

if user_exists:

but this condition passes every time. That is, it is always true for every name I pass in, whether it already exists or not.

I also tried,

if len(user_exists) > 0:

but get the error that a Gql query object has no len. If user_exists is a Gql query object, how could I extract some sort of list from this in order to simply check it's contents in the way I am attempting to?

I have in the past iterated through such an object with a for loop in a jinja template, and I assumed that this object could also be treated like an iterable, such as a list, in general.

Was it helpful?

Solution

Your code would work if you were calling .get() or .fetch(1) on the GqlQuery object.

Example:

user = db.GqlQuery("select * from User where user_id = :1", username).get()
if user:
    # now `user` will contain a value if the query returns a value or None if not

You should prefer use of query parameters to string-interpolation as using the API makes your code less vulnerable to SQL-injection attack.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top