Skip to content

Generated SQL missing fk in table definition #2119

Closed

Description

@JustasGl

Describe the bug
During migrate, the created SQL does not contain fk field.

To Reproduce
APP A:

class User(Model):
  id=...

APP B:
Create an abstract base class with an FK field

class GenericModel(Model):
  user = fields.ForeignKeyField(...)

Inherit through multiple abstract classes

ModelA(GenericModel):
  ....

ModelB(ModelA):
  ....

Create a concrete model

ConcreteModel(ModelB):
  ...

Run tortoise migrate APP B
Inspect the model metadata

async def create_model(self, model: type[Model]) -> None:
    model_sql_data = self._get_model_sql_data(model)

    model_statement = "\n".join([model_sql_data.table_sql, *model_sql_data.m2m_tables_sql])
    print("\n\nStatement: ")
    print(model_statement)
    await self._run_sql(model_statement)

Expected behavior
Created SQL has all the fields of the table.

Additional context
in tortoise/migrations/schema_editor/base.py
_get_model_sql_data creates sql from fields_db_projection which does not contain fk field.

The migration CLI builds an in-memory “state” of historical models for each app (in tortoise/migrations/schema_generator/state.py). When applying a migration, it calls state.reload_models(models_to_reload) for that app. Critically, only the current app’s models are loaded into the state. Any referenced models from other apps are not automatically included.

Activity

  1. added a commit that references this issue on Aug 30, 2026
    920625a
  2. added a commit that references this issue on Sep 10, 2026
    19e143c
  3. noy-solvin commented on Sep 15, 2026

    @noy-solvin
    Contributor

    Hi @waketzheng
    I've submitted PR #2278 that fixes this issue.
    Would love a review whenever you get a chance. Happy to adjust anything

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions