Reputation: 83
I'm trying to take the highest id and add one to make a new id. When I try to start it (it's at null as nothing is in there yet) it gives me this error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'result'
.
@app.route('/new-recipe', methods=['POST'])
def create_recipe(application):
data = request.get_json()
current_id = int(db.session.query(func.max(Recipes.id)).first())
# I've tried without int() too.
if current_id >= 1:
new_id = current_id + 1
new_recipe = Recipes(id=new_id)
return new_recipe.id
else:
new_recipe = Recipes(id=1)
return new_recipe.id
Upvotes: 0
Views: 726
Reputation: 1306
You can use .scalar()
to convert from a result to a value.
current_id = db.session.query(func.max(Recipes.id)).scalar()
See https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.scalar
I do, however, have a comment on your approach: it would be better to let the database generate the ids for you, because code like yours could behave unpredictably when multiple people are accessing /new-recipe
at the same time.
If you get the last id and then do an insert in a separate query (while not in a database transaction), someone else can insert a record with the same ID, as the one you're attempting to insert, before you. This would cause an error.
Upvotes: 2