Skip to content

Commit

Permalink
fix setting GFK by a callable, add test
Browse files Browse the repository at this point in the history
  • Loading branch information
PetrDlouhy committed Jan 23, 2025
1 parent 1aa6662 commit 0501aac
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
2 changes: 2 additions & 0 deletions model_bakery/baker.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,8 @@ def _handle_generic_foreign_keys(self, instance: Model, attrs: Dict[str, Any]):
ct_field_name = data["content_type_field"]
oid_field_name = data["object_id_field"]
value = data["value"]
if callable(value):
value = value()
if is_iterator(value):
value = next(value)
if value is None:
Expand Down
12 changes: 12 additions & 0 deletions tests/test_baker.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,18 @@ def test_create_model_with_contenttype_field(self):
assert isinstance(dummy, models.DummyGenericForeignKeyModel)
assert isinstance(dummy.content_type, ContentType)

def test_create_model_with_contenttype_with_content_object(self):
""" Test creating model with contenttype field and populating that field by function """
from django.contrib.contenttypes.models import ContentType

def get_dummy_key():
return baker.make("Person")

dummy = baker.make(models.DummyGenericForeignKeyModel, content_object=get_dummy_key)
assert isinstance(dummy, models.DummyGenericForeignKeyModel)
assert isinstance(dummy.content_type, ContentType)
assert isinstance(dummy.content_object, models.Person)


@pytest.mark.skipif(
not BAKER_CONTENTTYPES, reason="Django contenttypes framework is not installed"
Expand Down

0 comments on commit 0501aac

Please sign in to comment.