在Django ORM(Django 2.X)中,FilteredRelation()对象的用途是什么? [英] What is the usage of `FilteredRelation()` objects in Django ORM (Django 2.X)?

查看:312
本文介绍了在Django ORM(Django 2.X)中,FilteredRelation()对象的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到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 your QuerySet?


推荐答案

我认为文档本身-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 子句仅适用于素食比萨饼。


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 JOINs.

这篇关于在Django ORM(Django 2.X)中,FilteredRelation()对象的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆