SQLAlchemy Things: Unterschied zwischen den Versionen
Aus Froggis Wissenssammlung
Froggi (Diskussion | Beiträge) (Die Seite wurde neu angelegt: „=== Errors === If this appears (may differ a bit) AttributeError: 'int' object has no attribute '_sa_instance_state' then the variabel, in this case an int…“) |
Froggi (Diskussion | Beiträge) |
||
| Zeile 7: | Zeile 7: | ||
This happens moostly with one-to-many or many-to-many relationships. Make sure your date for the relationship is an ORM object | This happens moostly with one-to-many or many-to-many relationships. Make sure your date for the relationship is an ORM object | ||
| + | |||
| + | === Datensatz updaten === | ||
| + | |||
| + | 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. | ||
| + | |||
| + | 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() | ||
Aktuelle Version vom 26. August 2019, 12:49 Uhr
Errors
If this appears (may differ a bit)
AttributeError: 'int' object has no attribute '_sa_instance_state'
then the variabel, in this case an integer should have been an ORM object.
This happens moostly with one-to-many or many-to-many relationships. Make sure your date for the relationship is an ORM object
Datensatz updaten
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.
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()