Major bugfix for multiple annotations in API querysets #965
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
When performing multiple aggregation annotations on a queryset, the returned results are sometimes not correct. There is a very long discussion here
I thought I had fixed this in a previous PR by adding
distinct=True
to the annotations. However, this was not the correct solution. Thedistinct
operator only aggregates values which are distinct (unique) and while this resulted in correct behavior in my test cases at the time, it was not sufficient.Reproduce
This problem only appears in the REST API which uses queryset annotations to improve database performance.
To reproduce, create multiple stock items for a Part with the same quantity. For example, a Part has 10x stock items, each with quantity 5.
Instead of reporting
quantity=50
the API data will reportquantity=5
(because it ignores rows which do not have "unique" quantity values)...Solution
The "correct" solution appears to be to use the Django Subquery function.
However this is really unwieldy and difficult to understand.
Luckily, the django-sql-utils module makes this very easy!
Aggregating stock quantity against parts is now as simple as:
Fixes #954