dabapps / django-readers

A lightweight function-oriented toolkit for better organisation of business logic and efficient selection and projection of data in Django projects.
https://www.django-readers.org
BSD 2-Clause "Simplified" License
183 stars 7 forks source link

Add annotate pair function and refactor count and has to use it #56

Closed j4mie closed 1 year ago

j4mie commented 2 years ago

Note: this PR includes a backwards-incompatible change and as such will necessitate a 2.0 release. See this discussion for details.

The new docs branch (#59) will need to be updated to include this new function.

This exposes a general purpose annotate function under pairs which closely mirrors the annotate method on QuerySet, and sits below the existing count and has shortcut pair functions (and the soon-to-exist sum function).

If you're doing custom things with annotations, it replaces this:

spec = [
    ...,
    {
        "fiction_book_count": (
            qs.annotate(
                fiction_book_count=Count("book", filter=Q(book__is_fiction=True))
            ),
            producers.attr("fiction_book_count"),
        )
    },
    ...,
]

with this:

spec = [
    ...,
    {
        "fiction_book_count": pairs.annotate(
            fiction_book_count=Count("book", filter=Q(book__is_fiction=True))
        )
    },
    ...,
]

This feels more "Django" than our own count, has, sum functions, at the expensive of slightly more code and an additional import (the aggregate objects such as Count).