Home > database >  Django how to over ride created date
Django how to over ride created date

Time:11-24

We have a base model that sets a created and modified field:

class BaseModel(models.Model):
    created = models.DateTimeField(_('created'), auto_now_add=True)
    modified = models.DateTimeField(_('modified'), auto_now=True)
    ... other default properties

    class Meta:
        abstract = True

We use this class to extend our models:

class Event(BaseModel):

Is there a way to over ride the created date when creating new Events?

This is a stripped down version of our code. We are sending an array of event objects containing a created timestamp in our request payload. After the objects are added to the db, the created property is set to now and not the value from the payload.

I would like to still extend from the BaseModel as other areas of the code may not explicitly set a created value, in which case it should default to now.

events = []
for e in payload['events']:
    event = Event(
       created=datetime.datetime.fromisoformat(e['created'])
       name='foo'
    )
    events.append(event)
Event.objects.bulk_create(events)

CodePudding user response:

You can override the created field for your Event model with:

from django.utils.timezone import now

class Event(BaseModel):
    created = models.DateTimeField(default=now)

If you do not want this to show up for ModelForms and ModelAdmins by default, you can make use of editable=False [Django-doc]:

from django.utils.timezone import now

class Event(BaseModel):
    created = models.DateTimeField(default=now, editable=False)
  • Related