tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.5k stars 369 forks source link

default_connection for the model cannot be None #1188

Open Cikmo opened 2 years ago

Cikmo commented 2 years ago

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.

liangshan4 commented 1 year ago

bro, do you solve this?

Cikmo commented 1 year ago

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.

Cikmo commented 1 year ago

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.

liunux4odoo commented 1 year ago

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__

cikay commented 3 months ago

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.