Need to override django auto_now_add in pytest factory

Viewed 332

Due to auto_now_add in django models sent_at is not working in pytest factory. Need to overrive sent_at for pytest factory

class ABC(models.Model):
    x = models.ForeignKey(X, on_delete=models.CASCADE, related_name="xx")
    y = models.ForeignKey(Y, on_delete=models.CASCADE, related_name="yy")
    sent_at = models.DateTimeField(auto_now_add=True)


class ABCFactory(factory.django.DjangoModelFactory):
    x = factory.SubFactory(XFactory)
    y = factory.SubFactory(YFactory)
    sent_at = timezone.now() - timezone.timedelta(seconds=40)
1 Answers

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

In short, there are 2 solutions:

  • Remove the auto_now_add in your model field and instead use default=timezone.now. It will be fairly similar, except the field wont be read-only in the admin. But now you can easily override/update it
  • Override the _create method so that it sets the field and re-save the instance AFTER it was initially created
Related