Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Added
Fixed
^^^^^
- ``MigrationRecorder`` now uses parameterized queries; fixes MariaDB/MySQL rejecting ISO-8601 ``applied_at`` values. (#2132)
- ``db_default`` on ``ForeignKeyField``/``OneToOneField`` now propagates to the underlying ``<fk>_id`` column, so ``CREATE TABLE`` emits the ``DEFAULT`` clause for FK columns. (#2199)

1.1.7
-----
Expand Down
33 changes: 33 additions & 0 deletions tests/migrations/test_schema_editor_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,36 @@ class Meta:
sql = client.executed[0]
assert 'CREATE TABLE "widget"' in sql
assert "DEFAULT 'active'" in sql


@pytest.mark.asyncio
async def test_create_model_includes_db_default_on_fk() -> None:
"""CreateModel should include DEFAULT clause for FK columns with db_default."""

class Dc(Model):
id = fields.IntField(pk=True)
Comment thread
mixartemev marked this conversation as resolved.
Outdated

class Meta:
table = "dc"
app = "models"

class App(Model):
id = fields.IntField(pk=True)
Comment thread
waketzheng marked this conversation as resolved.
Outdated
dc: fields.ForeignKeyRelation[Dc] = fields.ForeignKeyField("models.Dc", db_default=2)

class Meta:
table = "app"
app = "models"

init_apps(Dc, App)

client = FakeClient("sql")
editor = TestSchemaEditor(client)

await editor.create_model(App)

assert len(client.executed) == 1
sql = client.executed[0]
assert 'CREATE TABLE "app"' in sql
assert '"dc_id"' in sql
assert "DEFAULT 2" in sql
2 changes: 1 addition & 1 deletion tortoise/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def init_fk_o2o_field(model: type[Model], field: str, is_o2o: bool = False) -> N
key_field = f"{field}_id"
key_fk_object.reference = fk_object
key_fk_object.source_field = fk_object.source_field or key_field
for attr in ("index", "default", "null", "generated", "description"):
for attr in ("index", "default", "null", "generated", "description", "db_default"):
setattr(key_fk_object, attr, getattr(fk_object, attr))
if is_o2o:
key_fk_object.pk = fk_object.pk
Expand Down
Loading