How does Sql Alchemy know what to update in a Patch, Put route in Flask route?

For example

@bp.route('/<int:id>', methods=['PATCH', 'PUT'])
def update(id: int):
    u = User.query.get_or_404(id)
    if 'username' in request.json:
        u.username = request.json['username']
    db.session.commit()
    return jsonify(u.serialize())

How does it know what to commit to the database ?

I would think it would work like POST does .
For example in a post route in flask

    u = User(
        username=request.json['username'],
        password=scramble(request.json['password'])
    )

    db.session.add(u)
    db.session.commit()

We have to add the variable u to the session. We don’t have to do this when we update.

Can someone please explain this to me?

I don’t know how exactly this is handled internally, but I guess that when you query existing records, they are already kept in the session. Meanwhile, the newly created record (object) needs to be added to session, to be saved.

Yeah, the only way I can make sense of it, is when we query existing records it somehow knows that the object is coming from the database.

I guess the real question is how does differentiate between an object that has come from the database that needs to be commited() and an object that I created manually?

Maybe I don’t understand sessions well enough ?

There’s some information in documentation, how it can be differentiated which state has specific object: State Management — SQLAlchemy 1.4 Documentation

Thank you!!! I think my lack of understanding with sessions has a lot to do with it.

I found this in the documentation . I think with this definition I can conclude that when a record is found in the database SqlAlchemy does some magic in the background and knows that some instance in the session has been updated.

Persistent - An instance which is present in the session and has a record in the database. You get persistent instances by either flushing so that the pending instances become persistent, or by querying the database for existing instances (or moving persistent instances from other sessions into your local session).

Ah! I think found your answer. Your reply made me look further into state.

Reading Essential.SQLAlchemy

The book goes on to say

_state
SQLAlchemy uses this property to  track whether a mapped object is "clean" (freshly fetched from the database),"dirty" (modified since fetching from the database) ore "new" (as yet unsaved to the database). So in a way we will call it Sql magic. 
Thank you!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.