Skip to content

Commit

Permalink
Fix support of auto_now fields in combination with _fill_optional (
Browse files Browse the repository at this point in the history
…#507)

* test: add test case for auto now with _fill_optional setting

* fix: auto now field should be skipped

* chore: update changelog
  • Loading branch information
mattwang44 authored Feb 11, 2025
1 parent 258dfb2 commit c0af32a
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Added

### Changed
- Fix support of `auto_now` and `auto_now_add` fields in combination with `_fill_optional`

### Removed

Expand Down
12 changes: 8 additions & 4 deletions model_bakery/baker.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ def _valid_quantity(quantity: Optional[Union[str, int]]) -> bool:
return quantity is not None and (not isinstance(quantity, int) or quantity < 1)


def _is_auto_datetime_field(field: Field) -> bool:
return getattr(field, "auto_now_add", False) or getattr(field, "auto_now", False)


def seed(seed: Union[int, float, str, bytes, bytearray, None]) -> None:
Baker.seed(seed)

Expand Down Expand Up @@ -513,10 +517,7 @@ def instance(
if isinstance(field, ForeignRelatedObjectsDescriptor):
one_to_many_keys[k] = attrs.pop(k)

if hasattr(field, "field") and (
getattr(field.field, "auto_now_add", False)
or getattr(field.field, "auto_now", False)
):
if hasattr(field, "field") and _is_auto_datetime_field(field.field):
auto_now_keys[k] = attrs[k]

if BAKER_CONTENTTYPES and isinstance(field, GenericForeignKey):
Expand Down Expand Up @@ -589,6 +590,9 @@ def _skip_field(self, field: Field) -> bool: # noqa: C901
else:
field.fill_optional = field.name in self.fill_in_optional

if _is_auto_datetime_field(field):
return True

if isinstance(field, FileField) and not self.create_files:
return True

Expand Down
13 changes: 13 additions & 0 deletions tests/test_baker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1162,3 +1162,16 @@ def test_make_with_auto_now(self, use_tz, settings):
assert instance.created == now
assert instance.updated == now
assert instance.sent_date == now

@pytest.mark.django_db
def test_make_with_auto_now_and_fill_optional(self):
instance = baker.make(
models.ModelWithAutoNowFields,
_fill_optional=True,
)
created, updated = instance.created, instance.updated

instance.refresh_from_db()

assert instance.created == created
assert instance.updated == updated

0 comments on commit c0af32a

Please sign in to comment.