Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removing relation child while updating nullable fk as None #1230

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions ormar/models/descriptors/descriptors.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ def __set__(self, instance: "Model", value: Any) -> None:
else:
# foreign key relation
instance.__dict__[self.name] = model
if value is None and instance.Meta.model_fields[self.name].nullable:
instance._orm.remove(self.name, getattr(instance, self.name))
instance.set_save_status(False)


Expand Down
12 changes: 12 additions & 0 deletions tests/test_relations/test_foreign_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,3 +440,15 @@ async def test_bulk_update_model_with_children():
is_best_seller=True
).all()
assert len(best_seller_albums_db) == 2


@pytest.mark.asyncio
async def test_fk_update_to_none():
async with database:
async with database.transaction(force_rollback=True):
fantasies = await Album.objects.create(name="Limitless")
track = await Track.objects.create(album=fantasies, title="Test1", position=1)
assert track.album.name == "Limitless"
track.album = None
updated_track = await track.update(_columns=["album"])
assert updated_track.album is None
Loading