Skip to content
Advertisement

Flask-Sqlalchemy : How to call a function everytime a new instance of a model is commited?

I want to make a new randomized user id every time a new user is committed. For this I am using the format : USR-<token>

The token is made by this function :

This function will be called in this database model :

I want the token to be new every time. But right now If I commit two User objects it gives me a Constraint Failed : Unique error. Also, I’m using SQLite for testing, if that makes any difference. The model is bigger than this but for the question I think only these parts are relevant.

Advertisement

Answer

I think you need to pass the make_token function AS the default argument, instead of its return value.

So you could try having your make_token function prepend “USR-” to the string:

And then pass that function as the default argument:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement