I am trying to create a class for a database using peewee in python. This results in nested classes due to peewee's use of a class named meta in the models. My question is, how do I define the database (=db) within the class Meta? Is there perhaps a better way?
import peewee as pe
class DataBase():
class SensorType(pe.Model):
name = pe.CharField(max_length=255, unique=True)
class Meta:
database = db
def ___init___(self,filename='sensors.db'):
db = pe.SqliteDatabase(filename)
db.connect()
db.create_tables([self.SensorType],safe=True)
def add_sensor(self,typeName):
type, created = self.SensorType.get_or_create(name=typeName)
return type, created
def get_sensors(self):
return self.SensorType.select().order_by(self.SensorType.name)
if __name__ == '__main__':
myDb = DataBase()
myDb.add_sensor('Test')
for type in myDb.get_sensors():
print(type.name)
I found that defining the classes within the __init__
function of my main class works. But it is probably not the preferred approach.
import peewee as pe
class DataBase():
def __init__(self,filename='sensors.db'):
db = pe.SqliteDatabase(filename)
db.connect()
class SensorType(pe.Model):
typename = pe.CharField(max_length=255, unique=True)
class Meta:
database = db
self.SensorType = SensorType
db.create_tables([self.SensorType],safe=True)
def add_sensor_type(self,typeName):
type, created = self.SensorType.get_or_create(typename=typeName)
return type, created
def get_sensor_types(self):
return self.SensorType.select()
if __name__ == '__main__':
myDb = DataBase()
myDb.add_sensor_type('Test')
for type in myDb.get_sensor_types():
print(type.id, type.typename)