在ManyToManyField上注释FilteredRelation不会返回任何内容 [英] Annotating a FilteredRelation on a ManyToManyField returns nothing

查看:53
本文介绍了在ManyToManyField上注释FilteredRelation不会返回任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模型

class User(AbstractUser):
    pass

class Report(Model):

    user = ForeignKey (
        "User",
        related_name="reports"
    )

    shared_doctors = ManyToManyField (
        "User",
        symmetrical = False,
        related_name="shared_reports"
    )

我在模型上有更多字段,但是为了缩短问题,我省略了它们.

I have more fields on the models, but I have omitted them in the interest of shortening the problem.

查询

User.objects.annotate(
    shared_reports_user = FilteredRelation(
        'shared_reports',
        condition = Q(shared_reports__user=user)
    )
).annotate(
    shared_reports_user_count = Count('shared_reports_user')
)

我将查询降低到了提供意外结果的基本级别.第一个注释中的 user User 的实例.

I have brought down the query to the base level which is giving unexpected results. user in the first annotate is an instance of User.

查询成功运行,但是生成的QuerySet没有 shared_reports_user 键,尽管它具有 shared_reports_user_count 键,其值为 0 .

The Query runs successfully, but the resulting QuerySet has no shared_reports_user key, though it has a shared_reports_user_count key, which has a value of 0.

据我从文档中了解到, FilteredRelation 接受将在其上进行过滤的模型上存在的字段,而命名参数 condition 则接受一个Q对象作为要应用于现有字段值的条件.这使我相信,第一个注释应该返回一个QuerySet,该注释集带有一个满足Q对象中指定条件的 shared_reports 子集.

As far as I understood from the documentation, FilteredRelation takes a field present on the Model that it will filter on, and a named argument, condition, that takes a Q object as a condition to be applied to the existing field value. This leads me to believe that the first annotation should return a QuerySet annotated with a subset of shared_reports satisfying the condition specified in the Q object.

我确定我的数据库中包含满足Q对象的值(我已经手动检查了数据),即使没有输出,我也希望对 shared_reports_user 键使用一个空的QuerySet.>.

I'm sure my database contains values satisfying the Q object (I have manually inspected the data), and even in case there is no output, I would have expected an empty QuerySet against the key shared_reports_user.

我错过了什么吗?

推荐答案

您可以使用条件聚合在Django 2.0中是这样的:

You can use Conditional aggregation in Django 2.0 like this:

User.objects.annotate(
shared_reports_user_count=Count('shared_reports', filter=Q(shared_reports__user_id=user.id))

这篇关于在ManyToManyField上注释FilteredRelation不会返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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