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.

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.