Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usage of `FilteredRelation()` objects in Django ORM (Django 2.X)?

I've seen Django 2.0 consists of FilteredRelation object in queryset. What is the usage of newly introduced FilteredRelation?

What I've looked into?

I observed Django 2.0 Documentation but I could not understand idea behind this FilteredRelation object.

I looked into following code. But I didn't get it.

>>> from django.db.models import FilteredRelation, Q
>>> Restaurant.objects.annotate(
...    pizzas_vegetarian=FilteredRelation(
...        'pizzas', condition=Q(pizzas__vegetarian=True),
...    ),
... ).filter(pizzas_vegetarian__name__icontains='mozzarella')

Main Question

Show now my question is that what is usage of FilteredRelation and when to use in your QuerySet?

like image 279
Devang Padhiyar Avatar asked Mar 28 '19 06:03

Devang Padhiyar


1 Answers

I think the documentation itself self-explanatory.

You could achieve the same result in,
Method-1

from django.db.models import FilteredRelation, Q

result_1 = Restaurant.objects.annotate(pizzas_vegetarian=FilteredRelation('pizzas', condition=Q(pizzas__vegetarian=True), ), ).filter(
    pizzas_vegetarian__name__icontains='mozzarella')

Method-2

result_2 = Restaurant.objects.filter(pizzas__vegetarian=True, pizzas__name__icontains='mozzarella')


You will get better performance with Method-1 since the filtering in the WHERE clause of the first queryset will only operate on vegetarian pizzas.


UPDATE

The Django #29555 ticket has more information regarding the usage and performance.

The FilteredRelation() not only improves performance but also creates correct results when aggregating with multiple LEFT JOINs.

like image 128
JPG Avatar answered Nov 07 '22 18:11

JPG