Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda