Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django queryset Datefield compare against today

I have a model where I have a start("inicia") and end("finaliza") date and I need to know if today is between those dates:

model:

class Promos(models.Model):
    nombre = models.CharField(max_length=20)
    codigo = models.CharField(max_length=10, blank=True, null=True)
    aplica_codigo = models.BooleanField(default=False)
    descuento = models.FloatField()
    porciento = models.BooleanField(default=False)
    inicia = models.DateField()
    finaliza = models.DateField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

the "inicia" and "finaliza" are the datefields that I want to check against today

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried the following:

today = date.today()
Promos.objects.filter(codigo = codigo_forma, inicia__gte = today,finaliza__lte=today).exists()

printing this is what I get:

today = 2022-08-25

print((Promos.objects.filter(codigo = codigo_forma).values("inicia", "finaliza")))

<QuerySet [{'inicia': datetime.date(2022, 8, 23), 'finaliza': datetime.date(2022, 11, 30)}]>

The result of the complete queryset is empty:
<QuerySet []>

I can´t figure out what is the correct format that I need to compare today against the model date fields.

>Solution :

You’ve mixed up gte and lte. As it stands, your code checks that inicia is after today and finaliza is before today. You want to switch the two, like this:

today = date.today()
Promos.objects.filter(codigo=codigo_forma, inicia__lte=today, finaliza__gte=today).exists()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading