default_connection for the model cannot be None
I am trying the example code from the README. When running await Tournament.create(name='New Tournament'), it returns the error tortoise.exceptions.ConfigurationError: default_connection for the model <class '__main__.Tournament'> cannot be None.
Tortoise does create the tables in the database, so the connection seems to be working.
I am using postgresql.
To Reproduce
class Tournament(Model):
id = fields.IntField(pk=True)
name = fields.TextField()
def __str__(self):
return self.name
await Tortoise.init(db_url=f"postgres://postgres:<password>@localhost:5432/tortoise",
modules={'models': ['test']})
await Tortoise.generate_schemas()
tournament = await Tournament.create(name='New Tournament')
Expected behavior Create a new row in the table.
bro, do you solve this?
bro, do you solve this?
Create a config dict, and include "default_connection": "default" in the app config.
This works for me:
tortoise_config = {
"connections": {"default": db_url},
"apps": {
"pnwapi": {
"models": ["database.models", "aerich.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "UTC",
}
await Tortoise.init(config=tortoise_config)
The example code does quite a bad job of onboarding, cause I don't think this is explained anywhere obvious.
I'd love to know why none of the examples show default_connection being explicitly set anywhere, yet the code fails if it doesn't get explicitly set.
If you run Tortoise.init in the models file, you should use models config like this:
await Tortoise.init({
db_url='...',
modules={'models': ['__main__'],
})
If you run Tortoise.init in another file and import model classess from a seperated file, you should use the module name instead of __main__
Another possibility is that if you navigate to the app folder then open the shell you encounter this issue.
When I run tortoise-cli -c app_name.setup_db.TORTOISE_ORM shell it is okay
However When I navigate to app then run tortoise-cli -c setup_db.TORTOISE_ORM shell I encounter the issue.
The solution above doesn't help me with version "0.24.0". I still get the same error despite the following
await Tortoise.init(
config={
"connections": {"default": os.environ["DB_URL"]},
"apps": {
"models": {
"models": ["models"],
"default_connection": "default",
},
},
},
use_tz=True,
timezone="UTC",
routers=["db_routers.DefaultRouter"],
)
This looks like the docs although I don't understand the apps portion of the config. My models are in models.py, but why do I need "models" as a key under "apps" and then as a key under "models"
The definition here: https://tortoise.github.io/setup.html#tortoise.Tortoise.init-parameters Could use a bit more verbiage than
modules=None¶ Dictionary of key: [list_of_modules] that defined “apps” and modules that should be discovered for models.
I keep wanting this to be more like Django but it appears to be a poor appoximation considering all the arcane chicken dances you need to get it working inside fastapi