Help with date filter in django


Good morning

I have a question about the filters for dates, I have a model called Absenteeism that has an attribute "start_date" and an "end_date", and I have problems with the filter of a query to create some graphs.

For example, I have a record of absenteeism with start_date = June 1, 2016 and end_date = June 3. If I make an inquiry from June 1 to 3 I get absenteeism and I can count the days, but if I do the consultation from 1 to 2, I get an empty list.

Could you please, in addition to helping me, also clarify about the use of modifiers in the filter as date__lt, date__gt, date__lte, date__gte? There's others? Is there a range?


class AusentismoBase(Novedad):
    fecha_inicio = models.DateField(verbose_name="Fecha Inicial")
    fecha_fin = models.DateField(verbose_name="Fecha Final")
    mes = models.IntegerField(validators=[no_negativo])
    quincena = models.IntegerField(validators=[no_negativo])
    hora_inicio = models.TimeField(verbose_name="Hora Inicial", blank=True, null=True)
    hora_fin = models.TimeField(verbose_name="Hora Final", blank=True, null=True)
    motivo = models.IntegerField(choices=MOTIVOS_AUSENTISMO, verbose_name="Motivo de Ausentismo")
    tipo_inc = models.IntegerField(choices=TIPOS_INCAPACIDAD, verbose_name="Tipo de Incapacidad", blank=True, null=True)
    eps = models.ForeignKey(Eps)
    arl = models.ForeignKey(Arl)
    edad = models.IntegerField(validators=[no_negativo])
    salario = models.IntegerField(validators=[no_negativo])

    def __unicode__(self):
        return (u"Ausentismo %s: (%s - %s)"%(self.persona, self.motivo, self.fecha_inicio)).strip() or "-"

    class Meta:
        unique_together = (("persona", "fecha_inicio"),)


def ausentismo_motivos_area_fechas(request, idArea=None, fechai=None, fechaf=None):
    resultado = iniciarResultadoTupla(MOTIVOS_AUSENTISMO)
    ausentismos = []
    form = AreaFechasForm()

    if request.method == 'POST':
        form = AreaFechasForm(request.POST)
        if form.is_valid():
            area = form.cleaned_data['area']
            fechai = form.cleaned_data['fechai']
            fechaf = form.cleaned_data['fechaf']
            return redirect('ausentismo_motivos_area_fechas',, fechai, fechaf)

    if idArea and fechai and fechaf:
        idArea = int(idArea)
        area = Area.objects.get(id=idArea)
        fechai = moddate.strptime(fechai, '%Y-%m-%d').date()
        fechaf = moddate.strptime(fechaf, '%Y-%m-%d').date()
        ausentismos = AusentismoBase.objects.filter(area=area, fecha_inicio__gte=fechai, fecha_fin__lte=fechaf)
        for a in ausentismos:
            i = a.motivo - 1
            x =
            y =
            for m in range(x, y+1):
                resultado[i] = llenarDatos(resultado[i], a.persona)

    form = AreaFechasForm(initial={'area':idArea, 'fechai':fechai, 'fechaf':fechaf})
    fila_0 = ['Motivo de Ausencia', 'B', 'C']
    graficas = [6, 4, 5]

    return render(request, 'plantilla_tipoempl.html', {
        'nombreGrafica': "Ausentismos Motivos Areas",
        'ejey': "Núm. Ausentismos",
        'ejex': "Motivos de Ausentismos",
        'resultadoJSON': json.dumps(resultado),
        'tipoEstadistica': "Ausentismos", #Clasificación de Estadísticas
        'resultado': resultado,
        'graficas': graficas,

        'fila_0': fila_0,
        'form': form,
        'filtro': "rango de fechas", #Sub Clasificación
        'ausentismos': ausentismos,
asked by Diana Carolina Hernandez 14.07.2016 в 18:02

1 answer


To make filters with ranges of dates or other costs, I always use

obj = models.filter(start_stamp__range=[inicio, fin])
answered by 02.08.2016 в 16:27