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

Do not handle GFK fields when the object is None #496

Merged
merged 1 commit into from
Aug 17, 2024
Merged
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 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)
amureki marked this conversation as resolved.
Show resolved Hide resolved

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