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

274
Vistas
Filter model by datetime in django

I need to filter model with (datetime.now() < end) My model

class Quiz(models.Model) :
    title = models.CharField(max_length=50)

    start = models.DateTimeFieldField(default="2021-10-10")
    end = models.DateTimeFieldField(default="2021-10-11")

My view

class GetQuizView(generics.ListAPIView) :
    def get_queryset(self):
        now = datetime.now()
        return Quiz.objects.filter(start = now)

    serializer_class = QuizListSerializer

But I can only filter with equal time, I can't use > or <

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You would use __gt, __lt, __gte and __lte

See the docs: https://docs.djangoproject.com/en/3.2/ref/models/expressions/

over 4 years ago · Santiago Trujillo Denunciar

0

You can write your queryset to look like this

class GetQuizView(generics.ListAPIView) :
    def get_queryset(self):
        now = datetime.now()
        end = "2021-10-11"
        return Quiz.objects.filter(start__range=[end, now])
     serializer_class = QuizListSerializer

Note that i hardcoded the value off end date which is not a good practice, you can easily specify the range (days) of your filter using the datetime library

Here is another code snippet

import pytz
from datetime import date, timedelta
from django.conf import settings
#timezone aware object
today = datetime.today().astimezone(pytz.timezone(settings.TIME_ZONE))
one_week = timedelta(days=7)
end_date = today-one_week
class GetQuizView(generics.ListAPIView) :
    def get_queryset(self):
        return Quiz.objects.filter(start__range=[end_date, today])
     serializer_class = QuizListSerializer

You can also use the django __lt, and __gt filter as per doc

Note: This essence of astimezone() is to make the query timezone aware, and then make the timezone inherit from your project timezone configuration as defined in your project settings.py

over 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