Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is DateTimeField with auto_now_add option enabled must has value in fixtures

I have model created field configurated as follows:

created = models.DateTimeField(auto_now_add=True)

In JSON fixtures I don't want to declare value for created, but when I try to load fixtures (loadata) I am getting error:

created may not be NULL

So I must provide created value in fixtures or there is an other way?

like image 742
keram Avatar asked Jan 31 '26 16:01

keram


1 Answers

You can use pre_save signal to process loaddata(fixtures)

@receiver(pre_save, sender=MyModel)
def pre_save_for_conference_code_fixture(sender, instance, **kwargs):
  if kwargs['raw']:
    instance.updated_at = timezone.now()
      if not instance.id:
        instance.created_at = timezone.now()

https://docs.djangoproject.com/en/3.1/ref/django-admin/#django-admin-loaddata

like image 82
Ford Guo Avatar answered Feb 02 '26 06:02

Ford Guo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!