问题
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