Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!