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

Refs #416 -- Allow combination of GFK and _fill_optional #438

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 7 additions & 2 deletions model_bakery/baker.py
Expand Up @@ -604,7 +604,7 @@ def _skip_field(self, field: Field) -> bool:

if field.name not in self.model_attrs:
if field.name not in self.rel_fields and (
field.null and not field.fill_optional
not field.fill_optional and field.null
):
return True

Expand Down Expand Up @@ -671,11 +671,16 @@ def generate_value(self, field: Field, commit: bool = True) -> Any: # noqa: C90
`attr_mapping` and `type_mapping` can be defined easily overwriting the
model.
"""
from django.contrib.contenttypes.fields import GenericForeignKey

is_content_type_fk = isinstance(field, ForeignKey) and issubclass(
self._remote_field(field).model, contenttypes.models.ContentType
)
is_generic_fk = isinstance(field, GenericForeignKey)
# we only use default unless the field is overwritten in `self.rel_fields`
if field.has_default() and field.name not in self.rel_fields:
if is_generic_fk:
generator = self.type_mapping[contenttypes.models.ContentType]
elif field.has_default() and field.name not in self.rel_fields:
if callable(field.default):
return field.default()
return field.default
Expand Down
5 changes: 5 additions & 0 deletions tests/test_filling_fields.py
Expand Up @@ -293,6 +293,11 @@ def test_iteratively_filling_generic_foreign_key_field(self):
assert dummies[1].content_type == expected_content_type
assert dummies[1].object_id == objects[1].pk

def test_with_fill_optional(self):
dummy = baker.make(models.DummyGenericForeignKeyModel, _fill_optional=True)
assert isinstance(dummy.content_type, ContentType)
assert dummy.content_type.model_class() is not None


@pytest.mark.django_db
class TestFillingForeignKeyFieldWithDefaultFunctionReturningId:
Expand Down