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

fix: auto now fields should be skipped #507

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
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 @@ -1124,3 +1124,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