djangounit-testing

How to override a Django DateTimeField(auto_now_add=True) value in a unit test?


I have a Django model field with auto_now_add=True. How do I override the value for this field in my test?

class ABC(models.Model):
    sent_at = models.DateTimeField(auto_now_add=True)


class ABCFactory(factory.django.DjangoModelFactory):
    sent_at = timezone.now() - timezone.timedelta(seconds=40)

Solution

  • Maybe checkout this solution posted in the factory_boy github: https://github.com/FactoryBoy/factory_boy/issues/102

    In short, there are 2 solutions: