Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
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?
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!!