Is DateTimeField with auto_now_add option enabled must has value in fixtures
Asked Answered
G

2

15

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?

Grozny answered 15/7, 2012 at 19:36 Comment(1)
I think that this is intentional and supports a good design. IMO, you should not hardcode timestamps in fixtures. Instead, try to create a management script that you will execute instead of loaddata from json fixtures. See docs.djangoproject.com/en/5.0/howto/custom-management-commandsTriphthong
M
-4

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

Millford answered 15/7, 2012 at 20:37 Comment(2)
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: docs.djangoproject.com/en/dev/ref/models/fields/#default)Modestomodesty
For reference, it is better to use django.utils's timezone function since it handles timezone. Otherwise you'll get a warning. (See: #18622507)Equivalent
F
3

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

Folse answered 24/11, 2020 at 10:42 Comment(0)
M
-4

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

Millford answered 15/7, 2012 at 20:37 Comment(2)
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: docs.djangoproject.com/en/dev/ref/models/fields/#default)Modestomodesty
For reference, it is better to use django.utils's timezone function since it handles timezone. Otherwise you'll get a warning. (See: #18622507)Equivalent

© 2022 - 2024 — McMap. All rights reserved.