[Answered ]-Filter queryset for many-to-many field for any foreign item matching specific criteria

1👍

You could do this by the use of Django ORM’s filter() method and passing it to the view as a context variable like so:

from django.shortcuts import render
from .models import BackupItems, CloudObjects
import datetime


def backup_items(request):
    future_date = datetime.datetime(2099, 12, 31)
    backup_items = BackupItems.objects.filter(cloudobject__removed_date=future_date).distinct()
    context = {'backup_items': backup_items}
    return render(request, 'backup_items.html', context)

This will return a queryset of BackupItems objects that have a CloudObject with a removed_date of 2099-12-31.
The distinct() method ensures that each BackupItem is returned only once.

👤ILoID

Leave a comment