appleLover
appleLover

Reputation: 15691

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?

Upvotes: 6

Views: 6814

Answers (1)

zero323
zero323

Reputation: 330093

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?

Upvotes: 15

Related Questions