问题
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 yourQuerySet
?
回答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 JOIN
s.
来源:https://stackoverflow.com/questions/55391181/what-is-the-usage-of-filteredrelation-objects-in-django-orm-django-2-x