[Django]-Django – Is it possible to prefetch multiple filters of a single field for a queryset?

3👍

With regards to your main question, you can use Prefetch..[Django-doc] object on the same field with different filters, but assign them with different to_attr values like this:

from django.db.models import Prefetch


Parent.objects.prefetch_related(
    Prefetch(
        "child_set", 
        queryset=Child.objects.filter(type="A"), 
        to_attr="child_set_a"
    ),
    Prefetch(
        "child_set", 
        queryset=Child.objects.filter(type="B"), 
        to_attr="child_set_b"
    ),
)

Leave a comment