From 7c2954d967de72f50c05446b10c2b6e498754325 Mon Sep 17 00:00:00 2001 From: Amit Vikram Date: Sat, 25 Nov 2023 01:40:01 +0530 Subject: [PATCH 1/2] Removing relation child while updating nullable fk as None --- ormar/models/descriptors/descriptors.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ormar/models/descriptors/descriptors.py b/ormar/models/descriptors/descriptors.py index 35f419470..73deccade 100644 --- a/ormar/models/descriptors/descriptors.py +++ b/ormar/models/descriptors/descriptors.py @@ -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) From ccbcd415d18b113b4786e8fa2c7664f04e0d555c Mon Sep 17 00:00:00 2001 From: Amit Vikram Date: Thu, 7 Dec 2023 01:11:38 +0530 Subject: [PATCH 2/2] Added test case to test fk update to none --- tests/test_relations/test_foreign_keys.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/test_relations/test_foreign_keys.py b/tests/test_relations/test_foreign_keys.py index e3412ed9f..5ff564888 100644 --- a/tests/test_relations/test_foreign_keys.py +++ b/tests/test_relations/test_foreign_keys.py @@ -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