1
votes

I have a user update function and I allow users to change their email address but the same address must be unique in the database so, before I update, I must check if their new email already exists in the database but the query I use to check that returns the same row. Example:

user = User.query.get(1)
user.email = '[email protected]'

if user.validate(): # The validate function performs a query to see if '[email protected]' is already taken
        user.save()

Now going into the validate function I have:

check = User.query.filter_by(User.email='[email protected]').first()
if check:
        # email already exists

Problem is that check holds the same user I'm editing. Sqlalchemy submits the update to the database but under some sort of transaction so my query returns the same user I'm editing. I've solved this by creating a second session object but seems like an overkill. Any better ideas? Am I making sense?

2

2 Answers

1
votes

Why not check, whether a user with a given e-mail address exists, before manipulating an existing user? You could e.g. write a standalone function for that:

def user_email_exists(email):
    return (not User.query.filter(User.email=email) == None)

Then call user_email_exists before the attempt to change the user object.

...

# User object to alter
user = ...

# the new email address, which needs to be checked
new_email_addr = '[email protected]' 

if user_email_exists(new_email_addr):
    raise SomeMeaningfulException() # or some `flash` message + a redirect
else:
    user.email = new_email_addr
    db.session.add(user)
    db.commit()

...
0
votes

The simplest way is probably just to add a second filter to the query inside your validate function. Instead of having it select any user with that email address, have it select any user with that email address and NOT the same username or user id. That way you're ensuring to only get a return if there is a different user with that email address.