Filter dates using foreignkey Django
I need to filter a variable between two models using a foreign key.
models.py
class Vuelo(models.Model):
fecha_de_vuelo = models.CharField(max_length=50)
.......
class Novedad(models.Model):
fecha_de_vuelo_novedad = models.ForeignKey(Vuelo, on_delete=models.CASCADE, related_name="fecha_de_vuelo_novedad", null=True, editable=False)
comandante_novedad = ......
view.py
def buscar_reporte_demoras(request):
if request.method == "GET":
inicio = request.GET.get("fecha_inicio", None)
fin = request.GET.get("fecha_fin", None)
criterio_1 = Q(fecha_de_vuelo_novedad__fecha_de_vuelo__gte = inicio)
criterio_2 = Q(fecha_de_vuelo_novedad__fecha_de_vuelo__lte = fin)
busqueda = Novedad.objects.all()
busqueda_con_filtro_fechas = busqueda.filter(criterio_1 & criterio_2)
context = {
'lista_vuelos': busqueda_con_filtro_fechas,
'criterio_fecha_inicio': inicio,
'criterio_fecha_fin': fin,
}
return render(request, '.........html', context)
The problem is that when I try to filter by "fecha_de_vuelo" using related_name = "fecha_de_vuelo_novedad" it doesn't give me any results.
Cual seria el error?
Agradezco la ayuda
There are a few issues with the code you provided.
fecha_de_vuelo is a CharField that is storing date. The correct way is to use a DateField or DateTimeField. In this case the filter is trying to compare 2 strings instead of 2 dates. This makes it susceptible to formatting bugs. ("28/11/2025" > "01/12/2025" is infact true).
So change
class Vuelo(models.Model):
fecha_de_vuelo = models.DateField() # or models.DateTimeField
.......
The second issue, you don't need to use a Q object to do an AND condition. Your query is straight forward and should be something like
busqueda_con_filtro_fechas = Novedad.objects.filter(
fecha_de_vuelo_novedad__fecha_de_vuelo__gte = inicio,
fecha_de_vuelo_novedad__fecha_de_vuelo__lte = fin,
) # This already means an `AND` condition
This assumes that fecha_de_vuelo is a DateField.
inicio and fin can be either datetime or date objects or can be strings in iso format "2025-11-28" or "2025-11-28 13:35:12".
If you are using the app in different timezones, I would really suggest you convert inicio and fin into timezone aware datetime objects before using it for any query.
I made those changes, but it still doesn't produce any results. It's as if the foreign key isn't being linked. But if I search directly in the Flight model, it does filter.