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

荒凉一梦 提交于 2020-01-14 02:55:13

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/55391181/what-is-the-usage-of-filteredrelation-objects-in-django-orm-django-2-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!