2
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.
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.
- [Answered ]-MultiValueDictKeyError: "'password'"
- [Answered ]-Celery .env variables not used in settings.py
- [Answered ]-Get null or empty query set in django
- [Answered ]-Django Moving lookup table to Redis
- [Answered ]-How to get attribute of a django model's foreign key object using getattr in python?
Source:stackexchange.com