[Answered ]-Django listview filter related field lookup by date

1👍

You need to filter the related items as well with a Prefetch object [Django-doc], so:

from django.utils.timezone import now


class vm(LoginRequiredMixin, ListView):
    model = Hypervisor
    template_name = 'vm_list_original.html'
    ordering = ['name']

    def get_queryset(self, *args, **kwargs):
        today = now().date()
        return (
            super()
            .get_queryset(*args, **kwargs)
            .filter(vm__date=today)
            .prefetch_related(
                Prefetch('vm_set', queryset=VM.objects.filter(date=today))
            )
            .distinct()
        )

Leave a comment