tortoise / tortoise/tortoise-orm

The foreign key cannot find the model

Open
#570 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

In my FastAPI project, I wrote the model in different files and imported through CONFIG_URL, but when I set the foreign key, it shows "No model with name 'role' registered in app' my_app'". I would like to ask what is the reason, thank you very much!

my config.json is

 {
  "connections": {
    "default": "mysql://root:123123@localhost:3306/boat"
  },
  "apps": {
    "my_app": {
      "models": [
        "database.user",
        "database.department",
        "database.role"
      ],
      "default_connection": "default"
    }
  },
  "use_tz": "False",
  "timezone": "UTC"
}

the models is

    username = fields.CharField(max_length=32)
    password = fields.CharField(max_length=255)
    department_id = fields.BigIntField()
    phone = fields.CharField(max_length=16)
    mode = fields.SmallIntField()
    login_time = fields.IntField(default=0)
    remember_token = fields.CharField(max_length=255, default="")
    role: fields.ForeignKeyRelation[Role] = fields.ForeignKeyField(
        "my_app.role", related_name="roles"
    )

    class Meta:
        table = "users"

the error is

tortoise.exceptions.ConfigurationError: No model with name 'role' registered in app 'my_app'.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with config.json and the model declarations in database.user, database.department, and database.role. Check how the configured app registers these models and how User's ForeignKeyField refers to Role. Done means the role model is registered under my_app and the configuration error no longer occurs.

Written by the indexing model from the issue text.

Assessment

Tech stack
fastapi, mysql, python
Domain
backend, databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.