4

I am trying to create a JSON fixture for one of my Django models.

The model is quite simple:

class Tag(models.Model):
    tag = models.CharField(max_length=50, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

My fixture is also simple:

[
  {
    "model": "myapp.tag",
    "pk": 1,
    "fields": {
      "tag": "Test 1"
    }
  },
{
    "model": "myapp.tag",
    "pk": 2,
    "fields": {
      "tag": "Test 2"
    }
  }
]

Unfortunately I get the following error when trying to run the fixture:

IntegrityError: NOT NULL constraint failed: myapp_tag.created_at

So it looks like auto_now_add=True doesn't get called when a fixture is run. I don't want to hardcode some date as that seems weird. (I also think hardcoding the PK is weird.)

Is there any way to get the created_at date to automatically use today?

And as a bonus, can the PK automatically auto-increment?

Thanks for your help.

Tom Brock
  • 920
  • 7
  • 29

1 Answers1

1

auto_now_add=True will only work if you django inserts a record to DB, other wise it wont work.

To make it work, write a simple python script and update json file with the current datetime and try this command to load the data to DB.