I've seen Django 2.0 consists of FilteredRelation
object in queryset. What is the usage of newly introduced FilteredRelation
?
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')
Show now my question is that what is usage of
FilteredRelation
and when to use in yourQuerySet
?
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.
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 JOIN
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With