From e8d1de09045658bae06ab14413f3f9a7cf5dc831 Mon Sep 17 00:00:00 2001 From: Rust Saiargaliev Date: Sat, 17 Aug 2024 09:34:19 +0200 Subject: [PATCH] Do not handle GFK fields when the object is None --- model_bakery/baker.py | 2 ++ tests/test_filling_fields.py | 15 +++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/model_bakery/baker.py b/model_bakery/baker.py index 929cc193..b6f16d6d 100644 --- a/model_bakery/baker.py +++ b/model_bakery/baker.py @@ -698,6 +698,8 @@ def _handle_generic_foreign_keys(self, instance: Model, attrs: Dict[str, Any]): content_type_field = data["content_type_field"] object_id_field = data["object_id_field"] value = data["value"] + if value is None: + continue if is_iterator(value): value = next(value) diff --git a/tests/test_filling_fields.py b/tests/test_filling_fields.py index ed1fb2e7..0fd4970a 100644 --- a/tests/test_filling_fields.py +++ b/tests/test_filling_fields.py @@ -277,14 +277,14 @@ def test_filling_IPAddressField(self): ) @pytest.mark.django_db class TestFillingGenericForeignKeyField: - def test_filling_content_type_field(self): + def test_content_type_field(self): from django.contrib.contenttypes.models import ContentType dummy = baker.make(models.DummyGenericForeignKeyModel) assert isinstance(dummy.content_type, ContentType) assert dummy.content_type.model_class() is not None - def test_filling_from_content_object(self): + def test_with_content_object(self): from django.contrib.contenttypes.models import ContentType profile = baker.make(models.Profile) @@ -296,7 +296,14 @@ def test_filling_from_content_object(self): assert dummy.content_type == ContentType.objects.get_for_model(models.Profile) assert dummy.object_id == profile.pk - def test_filling_generic_foreign_key_field_with_prepare(self): + def test_with_content_object_none(self): + dummy = baker.make( + models.DummyGenericForeignKeyModel, + content_object=None, + ) + assert dummy.content_object is None + + def test_with_prepare(self): from django.contrib.contenttypes.models import ContentType profile = baker.prepare(models.Profile, id=1) @@ -308,7 +315,7 @@ def test_filling_generic_foreign_key_field_with_prepare(self): assert dummy.content_type == ContentType.objects.get_for_model(models.Profile) assert dummy.object_id == profile.pk == 1 - def test_iteratively_filling_generic_foreign_key_field(self): + def test_with_iter(self): """ Ensures private_fields are included in ``Baker.get_fields()``.