Skip to content

Commit

Permalink
Do not handle GFK fields when the object is None (#496)
Browse files Browse the repository at this point in the history
  • Loading branch information
amureki authored Aug 17, 2024
1 parent bd865e7 commit 12a8570
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
2 changes: 2 additions & 0 deletions model_bakery/baker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
15 changes: 11 additions & 4 deletions tests/test_filling_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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()``.
Expand Down

0 comments on commit 12a8570

Please sign in to comment.