Updating a row using SQLAlchemy ORM

前端 未结 2 550
遇见更好的自我
遇见更好的自我 2021-01-18 06:22

Note: I am not using Flask-SQLAlchemy here, I\'m using SQLAlchemy ORM

I\'ve seen several answers on StackOverflow saying that this is a way to updat

相关标签:
2条回答
  • 2021-01-18 06:36

    Worked

    device = models.Device.query.filter(models.Device.device_identifier == device_identifier).first()
    
    setattr(device, 'updated_at', datetime.now())
    setattr(device, 'ip_address', ip_address)
    db.session.commit()
    

    Didn't work

    device.is_active = True
    device.id_address = ip_address
    device.updated_at = datetime.now()
    print(device.ip_address)
    db.session.commit()
    
    0 讨论(0)
  • 2021-01-18 06:56

    I believe you are looking for something like this for your update query:

    session.query(FoobarModel).filter(FoobarModel.id == foobar_id).update({'name': 'New Foobar Name!'})
    

    Since update() belongs to Query, and filter() does return a Query object, this will work, contrary to trying to call update() on your FoobarModel object (which does not have such a function) returned by Query.get(), see also here.

    As for looping over your properties and assigning them by name, you could do this with setattr and a dict, like this:

    foobar = session.query(FoobarModel).get(foobar_id)
    
    props = {'name': 'my new name'}
    
    for key, value in props.items():
        setattr(foobar, key, value)
    
    session.commit()
    session.flush()
    

    This is obviously a little pointless with just one property, but maybe it will come in handy at some point.

    0 讨论(0)
提交回复
热议问题