在Django ORM(Django 2.X)中,FilteredRelation()对象的用途是什么? [英] What is the usage of `FilteredRelation()` objects in Django ORM (Django 2.X)?
问题描述
我已经看到Django 2.0由queryset中的 FilteredRelation
对象组成。新引入的 FilteredRelation
的用途是什么?
I've seen Django 2.0 consists of FilteredRelation
object in queryset. What is the usage of newly introduced FilteredRelation
?
我观察到 Django 2.0文档,但我无法理解这个 FilteredRelation
对象背后的想法。
I observed Django 2.0 Documentation but I could not understand idea behind this FilteredRelation
object.
我查看了以下代码。
>>> 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
现在显示我的问题是
FilteredRelation
的用法是什么,何时在您的<$ c $中使用c> QuerySet ?
Show now my question is that what is usage of
FilteredRelation
and when to use in yourQuerySet
?
推荐答案
我认为文档本身-explanatory。
I think the documentation itself self-explanatory.
您可以在
方法1 < br>
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')
方法2
result_2 = Restaurant.objects.filter(pizzas__vegetarian=True, pizzas__name__icontains='mozzarella')
使用 Method-1 将获得更好的性能,因为 WHERE 第一个查询集的strong>子句仅适用于素食比萨饼。
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.
> Django#29555 票具有更多信息有关用法和性能。
FilteredRelation()
不仅可以提高性能,还可以创建
与多个 LEFT JOIN
s进行聚合时,结果正确。
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.
这篇关于在Django ORM(Django 2.X)中,FilteredRelation()对象的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!