Am new to Python. I am working on a project using Peewee ORM and Bottle.
My models.py file defines my models. My "db" variable is defined in my main file(index.py). I would like to access that same "db" instance using a global in the BaseModel Meta inner class below.
from peewee import *
import settings
class BaseModel(Model):
global db
class Meta:
global db
database = db
class Account(BaseModel):
created_ip = CharField(null=True)
created_on = DateTimeField()
I get the error below when i try to run the code
Traceback (most recent call last):
File "index.py", line 11, in <module>
from models import Account, Crawl, Site, Url
File "/api/models.py", line 4, in <module>
class BaseModel(Model):
File "/api/models.py", line 7, in BaseModel
class Meta:
File "/api/models.py", line 9, in Meta
database = db
NameError: name 'db' is not defined
Can i access the global "db" in the inner class, is there an easier way to use the global "db" instance in another file?
Thank you
Don't define your db
database instance inside the main file. Keep it with your models in the models.py
. And, according to the documentation, it is recommended to have a base model that would have the database
"meta" attribute defined:
db = SqliteDatabase('my_app.db')
class BaseModel(Model):
class Meta:
database = db
class User(BaseModel):
username = CharField()