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

159
Visualizações
Auto-incrementing Django DateField

How does one create a DateField, which automatically increments by 1 day in the way that the pk field does?

For example, I would create a new object, this would be of 16/04/2017, the next object would be of 17/04/2017, even if they are both submitted on the same day.

How would I do this?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

How about override the model's save method like this:

from datetime import datetime, timedelta

from django.db import models


class MyModel(models.Model):
    date = models.DateField()  # the below method will NOT work if auto_now/auto_now_add are set to True

    def save(self, *args, **kwargs):
        # count how many objects are already saved with the date this current object is saved
        date_gte_count = MyModel.objects.filter(date__gte=self.date).count()
        if date_gte_count:
            # there are some objects saved with the same or greater date. Increase the day by this number.
            self.date += timedelta(days=date_gte_count)
        # save object in db
        super().save(*args, **kwargs)

Of course, the above can be implemented using Django signals. The pre_save one.

about 4 years ago · Santiago Trujillo Relatório

0

So I worked this out using parts of Nik_m's answer and also some of my knowledge.

I essentially made a while loop which kept iterating over and adding a day, as opposed to Nik_m's answer which doesn't work after the third object due to a lack of iteration.

  def save(self, *args, **kwargs):
    same_date_obj = Challenge.objects.filter(date=self.date)

    if same_date_obj.exists():
        while True:
            if Challenge.objects.filter(date=self.date).exists():
                self.date += timedelta(days=1)
            else:
                break
    super().save(*args, **kwargs)

EDIT: This answer is no longer valid, it requires a while loop and thus an indefinite amount of queries. @Nik_m's modified answer is better.

about 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