auto_now_add overrides factoryboy params
See original GitHub issueSay I have a model:
class Foo(models.Model):
foo = models.DateField(auto_now_add=True)
with a trivial factory FooFactory, if I then do:
print FooFactory(foo=date(2001, 1, 1)).foo
it prints the current date, not the one I specified. To me this is a violation of principle of least surprise.
Issue Analytics
- State:
- Created 10 years ago
- Reactions:9
- Comments:6 (2 by maintainers)
Top Results From Across the Web
Reference — Factory Boy stable documentation
The extra parameters attached to a Factory are declared through a Params class. ... A Factory subclass may override a couple of class...
Read more >Temporarily disable auto_now / auto_now_add - Stack Overflow
I want to overwrite the two date fields for some model instances (used when migrating data). The current solution looks like this:
Read more >Testing Models with Django using Faker and Factory Boy
The factory_boy library(modeled after Factory Girl in Rails) the generation of data for tests. ... Build a Company instance and override company
Read more >Two Scoops of Django: Best Practices for Django 1.8
12.3 Pattern 3: Overriding the Clean Stage of Validation . ... auto now add. If so, you will ... parameter to ValidationError as...
Read more >Two Scoops of Django: Best Practices for Django 1.8
12.3 Pattern 3: Overriding the Clean Stage of Validation . ... auto now add. If so, you will ... parameter to ValidationError as...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Hi,
That’s a built-in “feature” of Django: when a field has
auto_now_add=True
, Django will override any provided value withdjango.utils.timezone.now()
; this happens ‘‘after’’ factory_boy’s code runs.You have two options:
_create
function:auto_now_add=True
with thedefault
keyword argument to models:Note the lack of brackets in
default=timezone.now
; this could also be written asdefault=lambda: timezone.now()
to be more explicit.I have personnally chosen the second version, which lets me override
created_at
fields easily in tests.Here is my way to do it in a universal way with freeze gun https://stackoverflow.com/a/70364787/1731460