Create, Read, Update, Delete

.select()  Displays records
.create    Creates a new record
.save()    Updates an existing record in the db
.get()       Gets a single record from the db
.delete_instance() Deletes a row from a table


[queries.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': 'basharghadanfar', 'points': 56132} ,
    {'username': 'ahmadahmad', 'points': 16523} ,
    ]

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

def top_student():
  student = Student.select().order_by(Student.points.desc()).get()  

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

Database Testing

Testing the newly created database:

>>> python students.py
>>> ls
students.db students.py
>>> sqlite3 students.db
sqlite> .tables
student
sqlite> select * from students;     
sqlite> .exit
>>>

.tables Displays all available tables

select Selects data from table

.exit Exits sqlite command line