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 Meet Peewee, Our ORM

Santosh Pillai
Santosh Pillai
3,052 Points

Creating and using more than 1 database dynamically using peewee

Hi,

This is what I want to do:

  1. I want to create three database
  2. Add data to this databases (making sure that data is added to correct database).
  3. Retrive data from these databases.

Here's what I've done so far.

from peewee import *

database_proxy = Proxy() # Create a proxy for our db.

class BaseModel(Model): class Meta: db = database_proxy # Use proxy for our DB.

class Overview(BaseModel): date = DateTimeField(unique=True) auto_total = CharField() .... ... ..

def initialize(loc): """ Initialising database based on the some condition""" if "Performance" in loc: db = SqliteDatabase('Performance.db', threadlocals=True) elif "Snapchat" in loc: db = SqliteDatabase('Snapchat.db', threadlocals=True) elif "Intelligence" in loc: db = SqliteDatabase('Intelligence.db', threadlocals=True) database_proxy.initialize(db) db.connect() db.create_tables([Overview], safe=True)

def add_data(test_date, time_duration, auto, manual, total): """ adding data to database""" try: Overview.create(date=test_date, auto_total=auto[1], auto_pass=auto[2], auto_fail=auto[3], .... ... .. print("New Row Added") except IntegrityError: update_results = Overview.get(date=test_date) update_results.auto_total = auto[1] update_results.auto_pass = auto[2] ..... .... ..

def get_rows(): cursor = Overview.select().order_by(Overview.date.desc()) print(cursor)

for test in cursor:
    print()

I's able to create three data bases at run time. But I,m not sure

  1. How to add data to the correct database?
  2. How to retrieve data from the correct database?

Any suggestions will be really helpful.

Thanks Santosh