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

Gilang Ilhami
Gilang Ilhami
12,045 Points

column username is not unique

i got an error, but it's not the same one as in the video

File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 115, in rera
ise                                                                                              
    raise value.with_traceback(tb)                                                               
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 2780, in exe
cute_sql                                                                                         
    cursor.execute(sql, params or ())                                                            
peewee.IntegrityError: column username is not unique

students.py

from peewee import *

db = SqliteDatabase('students.db')

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

    class Meta:
        database = db

students = [
    {'username': 'kennethlove',
     'points': 4888},
    {'username': 'chalkers',
     'points': 11912},
    {'username': 'joykesten2',
     'points': 7362},
    {'username': 'craigsdennis',
     'points': 4879},
    {'username': 'davemcfarland',
     'points': 14717}
]

def add_students():
    for student in students:
        Student.create(username=student['username'],
                      points=student['points'])


if __name__ == '__main__':
    db.connect()
    db.create_tables([Student], safe=True)
    add_students()

1 Answer

Ryan S
Ryan S
27,276 Points

Hi Gilang,

At about 3:45 in the video, Kenneth goes into detail about why this error is occurring and how to correct it by using a try/except block.

The specific wording of the errors may not be exactly the same, but they certainly describe the same thing: an IntegrityError due to a 'username' not being unique.