Annotating a FilteredRelation on a ManyToManyField returns nothing

落花浮王杯 提交于 2020-01-16 19:32:09

问题


Models

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.

Query

User.objects.annotate(
    shared_reports_user = FilteredRelation(
        'shared_reports',
        condition = Q(shared_reports__user=user)
    )
).annotate(
    shared_reports_user_count = Count('shared_reports_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.

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.

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.

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.

Am I missing something?


回答1:


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))


来源:https://stackoverflow.com/questions/59472592/annotating-a-filteredrelation-on-a-manytomanyfield-returns-nothing

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