Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
Django how to over ride created date

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)
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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)
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda