Python Using Databases in Python Meet Peewee Queries Are Your Friend

Kortney Field
Kortney Field
13,928 Points

Students are being filtered to top student properly.

When I run the code, I was given davemcfarland as the top student (great). Then I increased the points for kennethlove. I was still getting davemcfarland back. (I saved the code before running). I tried exiting and reopening the workspaces. I then ran it again and was getting craigsdennis back (clearly has the least amount of points). So I closed and opened the workspaces again. I am getting davemcfarland again. (I didn't change anything to the code between tests).

Here is my code. Is there something with my code or something wrong with my workspaces?

from peewee import * 

db = SqliteDatabase('students.db')

class Student(Model):
  username= CharField(max_length=225, unique=True)
  points = IntegerField(default=0)
  class Meta: 
    database = db 

students = [
  {'username': 'kennethlove', 
   'points': 14788},
  {'username': 'chalkers', 
   'points': 11912},
  {'username': 'joykesten2', 
   'points': 7363},
  {'username': 'craigsdennis', 
   'points': 4079}, 
  {'username': 'davemcfarland', 
   'points': 14700},

def add_students():
    for student in students:
        except IntegrityError:
            student_record = Student.get(username=student['username'])
            student_record.points = student['points']

def top_student():
  student =
  return student

if __name__ == '__main__':
  db.create_tables([Student], safe=True)
  print("Our top student right now is: {0.username}".format(top_student()))
Steven Parker
Steven Parker
203,731 Points

You can share the entire workspace by making a snapshot and posting the link to it.

2 Answers

Steven Parker
Steven Parker
203,731 Points

I don't understand the part about getting Craig's name, but I think I see the other issue.

The database is loaded from the file "students.db", which already exists in the workspace, and contains names that conflict with those in the "students" list. That causes the "add_students" function to fail, so you just get the results based on what was in the file to start with.

So to see the different results, you just need to delete the old database file before you run the Python program. I gave it a try for confirmation, and it worked.