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

Try/Except throwing internal error

Pasting the code below - everything worked right up until the try/except was added to catch the duplicates. I'm using postgreSQL, but looking at the docs there shouldn't get a difference on create? Anyone see anything?

Traceback (most recent call last):
  File "/Users/bmac413/Dev/pythonpostgres/Treehouse/students.py", line 39, in <module>
    add_students()
  File "/Users/bmac413/Dev/pythonpostgres/Treehouse/students.py", line 30, in add_students
    student_record = Student.get(username=student['username'])

peewee.InternalError: current transaction is aborted, commands ignored until end of transaction block

My code:

from peewee import *

psql_db = PostgresqlDatabase('students',user='postgres')

class Student(Model):
    username = CharField(max_length=255,unique=True)
    points = IntegerField(default=0)

    class Meta:
        database = psql_db

students = [
    {"username":"Bob",
     "points": 456},
    {"username": "John",
     "points": 344},
    {"username": "Jim",
     "points": 476},
    {"username": "Greg",
     "points": 500},
    {"username": "Pat",
     "points": 329},
]

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()



if __name__ == "__main__":
    psql_db.connect()
    psql_db.create_tables([Student], safe=True)
    add_students()
juanreyes7
juanreyes7
4,070 Points

The same thing happened to me, using Postgresql. I'll post here if I find a solution.