Skip to content

Commit

Permalink
Fix SaferAlterFieldSetNotNull for custom-named fields
Browse files Browse the repository at this point in the history
Prior to this change, this operation didn't work for fields that had
column names in the database that didn't match their names (such as
ForeignKey fields, which have an "_id" suffix).

This commit changes that by obtaining the column name from the model's
meta class instead.
  • Loading branch information
marcelofern committed Feb 10, 2025
1 parent 88285cb commit 4cd1556
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to

## [Unreleased]

### Fixed

- `SaferAlterFieldSetNotNull` did not work when the field dropping the NOT NULL
constraint was a ForeignKey. An error such as:
`django.db.utils.ProgrammingError: column "foo" does not exist` would have
been raised instead.

## [0.1.17] - 2025-01-14

### Added
Expand Down
10 changes: 6 additions & 4 deletions src/django_pg_migration_tools/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -1111,11 +1111,12 @@ def database_forwards(
from_state: migrations.state.ProjectState,
to_state: migrations.state.ProjectState,
) -> None:
model = to_state.apps.get_model(app_label, self.model_name)
NullsManager().set_not_null(
app_label,
schema_editor,
model=to_state.apps.get_model(app_label, self.model_name),
column_name=self.name,
model=model,
column_name=model._meta.get_field(self.name).column,
)

def database_backwards(
Expand All @@ -1125,11 +1126,12 @@ def database_backwards(
from_state: migrations.state.ProjectState,
to_state: migrations.state.ProjectState,
) -> None:
model = to_state.apps.get_model(app_label, self.model_name)
NullsManager().set_null(
app_label,
schema_editor,
model=to_state.apps.get_model(app_label, self.model_name),
column_name=self.name,
model=model,
column_name=model._meta.get_field(self.name).column,
)

def describe(self) -> str:
Expand Down
1 change: 0 additions & 1 deletion tests/django_pg_migration_tools/test_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -1693,7 +1693,6 @@ def test_when_not_allowed_to_migrate_by_the_router(self):
# the router.
assert len(queries) == 0

@pytest.mark.xfail
@pytest.mark.django_db(transaction=True)
def test_operation(self):
project_state = ProjectState()
Expand Down

0 comments on commit 4cd1556

Please sign in to comment.