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 Using Databases in Python Meet Peewee Queries Are Your Friend

Confused on IntegrityError

I'm still a bit confused on why the code rose an error. Why is it adding the same username more than once? Can someone break it down further for me?

2 Answers

Hi jayda,

The code doesn’t attempt to add the same username more than once during one execution of the file, but the database that the records are saved too persists.

So what Kenneth is explaining is that running the file a second time (or third, or fourth, etc) an error pops up. The file is attempting to add usernames to the database which were already added to the database the first time the file was run. And since the model created for the database states that the username must be unique, the database is throwing an error each time it confronts a username that is already in the database (which are all of them).

I imagine what makes this truly confusing is the fact that running a file back to back the way Kenneth does in the video is impractical. He’s simply trying to explain a concept and offer an example of why you would want to add a try...except block to your code.

Consider a situation where you’ve created a PAC Man style game on the web that uses a database in the backend to store user info and total points. The front end takes the info from the database and both shows it to the user so the user will know how many points they’ve accumulated, and at the end of each level it sends the new point total to the database so that it can be saved. If the way you’ve programmed this to work is by creating a new row in the database each time you send the new point total to the database, then you’ll run into a problem. Because the database already has the username in its records, it stops updating the user’s point total (because the database is like, “this user is already in my database with a point total of zero (from when she first signed up), I don’t know what to do with this different information so I’ll just dismiss it”. To combat that, you’ll ask the database for the record of the username/user that’s logged in (using a get request), and you’ll tell the database not to CREATE a new record, but to UPDATE that current one.

Does that make a little more sense? If not, let me know and I’ll try again.

Okay that makes a lot more sense. Thank you so much!!