14

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?

keram
  • 2,321
  • 4
  • 24
  • 29

2 Answers2

2

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

alias51
  • 8,178
  • 22
  • 94
  • 166
Ford Guo
  • 957
  • 9
  • 18
-3

Try

import datetime
created = models.DateTimeField(default=datetime.datetime.now)

And about why this happening you can read over here: Django auto_now and auto_now_add and Django model field default

Community
  • 1
  • 1
oburejin
  • 207
  • 1
  • 9
  • 12
    This is a bad suggestion. datetime.datetime.now() will be evaluated when the models are loaded. The default datetime for this created field will be when the server was last started, basically. Edit: Here's what oburejin actually wanted. created = models.DateTimeField(default=datetime.datetime.now) (Default takes a callable object, for calling at actual instantiation time. See: https://docs.djangoproject.com/en/dev/ref/models/fields/#default) – Hovis Biddle May 20 '13 at 20:11
  • For reference, it is better to use django.utils's timezone function since it handles timezone. Otherwise you'll get a warning. (See: https://stackoverflow.com/questions/18622007/runtimewarning-datetimefield-received-a-naive-datetime) – Max Sirwa Dec 31 '19 at 17:09