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

Databases

Aaron Banerjee
Aaron Banerjee
6,876 Points

python database integrity question

Hi everyone. I am relearning python databases and had some questions about how they work, more importantly, the integrity error associated with them which we learned in one of the videos.

   def add_students():
  for student in students:
    try:
      Student.create(username=student['username'],points = student['points'])
    except IntegrityError:
      student_record = Student.get(username=student['username'])
      student_record.points=student['points']
      student_record.save()
      db.connect()
     db.create_tables([Student],safe=True)
      add_students()
      print("Our top student right now is: {0.username}".format(top_student()))

do we use the try and except above in add_students in order to check if a username already exists in the database. so that we should therefore just change the points?

2 Answers

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Aaron,

Yes, you are exactly right. The IntegrityError is triggered if creating a record violates the unique constraint set on the student's name (i.e., there can only be one student record with a particular name). We can deduce from the violation of the unique constraint that there must already exist a student with that name, and so we can update their existing record instead of replacing it with a new one.

Cheers

Alex

Aaron Banerjee
Aaron Banerjee
6,876 Points

on all databases, do we need a function like this in order to stop integrity errors?