Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy Insert w/ Dictionary

For this situation assume there is a table declared with the declarative base called Game, with column names "espn_game_id" and "a_name". There is a session object open under the variable "s". So this works:

s.add(Game(espn_game_id=888, a_name='lol'))
s.commit()

This fails:

n = {"espn_game_id": 888, "a_name": 'lol'}
s.add(Game(n))
s.commit()

This works (assuming there is already an entry with espn_game_id==888):

n = {"a_name": 'lol'}
s.query(Game).filter(Game.espn_game_id==888).update(n)
s.commit()

Why does the second case fail and is there a way to get that type of syntax to work here?

like image 763
appleLover Avatar asked Sep 13 '13 10:09

appleLover


1 Answers

Try to replace:

s.add(Game(n))

with:

s.add(Game(**n))

Let's assume you have function like this:

def foo(**kwargs):
    print [item for item in kwargs.items()]

It expects keyword not positional arguments so this will work:

foo(**{'foo': 1, 'bar': 2}) 

and this will fail:

foo({'foo': 1, 'bar': 2}) 

For a better explanation you should read *args and **kwargs?

like image 147
zero323 Avatar answered Oct 19 '22 19:10

zero323