Skip to content

Commit c0af32a

Browse files
authored
Fix support of auto_now fields in combination with _fill_optional (#507)
* test: add test case for auto now with _fill_optional setting * fix: auto now field should be skipped * chore: update changelog
1 parent 258dfb2 commit c0af32a

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
1010
### Added
1111

1212
### Changed
13+
- Fix support of `auto_now` and `auto_now_add` fields in combination with `_fill_optional`
1314

1415
### Removed
1516

model_bakery/baker.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ def _valid_quantity(quantity: Optional[Union[str, int]]) -> bool:
7070
return quantity is not None and (not isinstance(quantity, int) or quantity < 1)
7171

7272

73+
def _is_auto_datetime_field(field: Field) -> bool:
74+
return getattr(field, "auto_now_add", False) or getattr(field, "auto_now", False)
75+
76+
7377
def seed(seed: Union[int, float, str, bytes, bytearray, None]) -> None:
7478
Baker.seed(seed)
7579

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

516-
if hasattr(field, "field") and (
517-
getattr(field.field, "auto_now_add", False)
518-
or getattr(field.field, "auto_now", False)
519-
):
520+
if hasattr(field, "field") and _is_auto_datetime_field(field.field):
520521
auto_now_keys[k] = attrs[k]
521522

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

593+
if _is_auto_datetime_field(field):
594+
return True
595+
592596
if isinstance(field, FileField) and not self.create_files:
593597
return True
594598

tests/test_baker.py

+13
Original file line numberDiff line numberDiff line change
@@ -1162,3 +1162,16 @@ def test_make_with_auto_now(self, use_tz, settings):
11621162
assert instance.created == now
11631163
assert instance.updated == now
11641164
assert instance.sent_date == now
1165+
1166+
@pytest.mark.django_db
1167+
def test_make_with_auto_now_and_fill_optional(self):
1168+
instance = baker.make(
1169+
models.ModelWithAutoNowFields,
1170+
_fill_optional=True,
1171+
)
1172+
created, updated = instance.created, instance.updated
1173+
1174+
instance.refresh_from_db()
1175+
1176+
assert instance.created == created
1177+
assert instance.updated == updated

0 commit comments

Comments
 (0)