Skip to content

Commit

Permalink
Refs #416 -- Allow combination of GFK and _fill_optional
Browse files Browse the repository at this point in the history
  • Loading branch information
amureki committed Aug 14, 2023
1 parent d51629b commit 9ca826a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
9 changes: 7 additions & 2 deletions model_bakery/baker.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit 9ca826a

Please sign in to comment.