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

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?

Menno Willemse
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Menno Willemse
Python Development Techdegree Graduate 9,594 Points

Hi Brecht,

I know i am a bit late, but just in case anyone is wondering:

The problem seems to be in the db.create_table(Student, safe=True) line

If you try amending it to db.create_tables([Student], safe=True) it should work.