Skip to content

Generated SQL missing fk in table definition #2119

@JustasGl

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.

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