Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

sqlite woes...

So, I have a database with a Player model. In that model I have 'name' and 'games_played' which I need to update by 1 every time the player plays the game. The best way I can figure how to do that is to get the current 'games_played' from the current Player.name, do the calculation, and then update Player with the new games_played. The trouble I'm having is getting that number from the database. I'm sure there is an easy explanation, and probably an easier way to go about it, but any advice would be greatly appreciated.

Thanks,

ar

Could you post your code here so we can more easily see what you are attempting. That way any solution proposed will match your programming style.

2 Answers

yes, I suppose that would be helpful :-) I actually figured out this problem with this code:

def update_player(current_player, correct):
    '''Update the database with player stats'''
    players = Player.select()
    for player in players:
        if current_player == player.name.lower():
            new_game_count = player.games_played
    new_game_count += 1
    Player.update(games_played = new_game_count).where(Player.name == current_player).execute()  

I suspect there might be an easier way. For example, is there a way for me to just directly addressing a single record with out trolling the entire database for a name match?

You could definitely just address a single record using the .where() and .update() methods without having to use the for loop or the if statement. That should stream-line the code quite a bit but still retain the same functionality.

I think it could look something like this:

def update_player(current_player, correct):
    '''Update the database with player stats'''
    update = Player.update(games_played += 1).where(Player.name.lower() == current_player)
    update.execute()

Mind you I haven't tested this code so if you implement it and find it doesn't work please tell me so and I'll take another look at what I wrote so that I can make it work.