Search code examples
djangodjango-modelstimezonedatefield

comparing DateField with timezone.now().date()


I am trying to compare DateFIeld with timezone.now().date() but its not giving the desired output:

models.py:

class Holiday_List(models.Model):
name=models.CharField(max_length=30)
holi_day=models.DateField(default=timezone.now())
def __str__(self):
    return '{}---{}'.format(self.name, self.holi_day)

admin.py:

def refresh():
flag=0
din=Holiday_List.objects.all()
for aaj in din:
    if aaj.holi_day==timezone.now().date():
        flag=1
        break;
if(flag==0):
    # some code to be executed

I have objects with today's date in the Holiday_List but still the flag value is not being set to 1 and the code gets executed after calling the function.


Solution

  • You can filter this with:

    def refresh():
        flag = Holiday_List.objects.filter(
            holi_day=timezone.now().date()
        ).exists()
        if not flag:
            # …

    Note that flag is True in case there exist Holiday_List objects with holi_day as today, and thus False otherwise. The if not flag will thus be triggered if today is not a holiday.