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

Brecht Philips
Brecht Philips
8,863 Points

Username is not Unique

Hi i'm following the code in pycharm with sqlite and everything works i can create a table i can look at it but the unique part doesn't work.

This is the students class

From peewee import everything

from peewee import *

Make a slqlite connection and creates the database if it doesn't excist

db = SqliteDatabase('students.db')

Models in peewee are classes

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

# Tell the model to witch database this belong to!
class Meta:
    database = db

students = [ {'username':'BrechtPhilips', 'points':7000}, {'username':'SanneDeSmedt', 'points':100}, {'username':'King', 'points':10000}, {'username':'Liesse', 'points':1}, {'username':'HannePhilips', 'points':2980} ]

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

a common pattern for making code only run when the script is run

and not when it's imported

if name == 'main': db.connect() db.create_table(Student,safe=True) add_students()

But when i look at my database how it's created i get this sql statement: CREATE TABLE "student" ("id" INTEGER NOT NULL PRIMARY KEY, "username" VARCHAR(255) NOT NULL, "points" INTEGER NOT NULL)

Does anybody have ideas what i'm doing wrong?