diff --git a/CHANGELOG.md b/CHANGELOG.md index f3484827c7..6ddf14e18d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Added `order_queryset` report helper function in [#10439](https://github.com/inventree/InvenTree/pull/10439) + ### Changed ### Removed diff --git a/docs/docs/report/helpers.md b/docs/docs/report/helpers.md index ec42fc8056..ec47feca8a 100644 --- a/docs/docs/report/helpers.md +++ b/docs/docs/report/helpers.md @@ -84,9 +84,32 @@ To return an element corresponding to a certain key in a container which support A number of helper functions are available for accessing database objects: +### order_queryset + +The `order_queryset` function allows for ordering of a provided queryset. It takes a queryset and a list of ordering arguments, and returns an ordered queryset. + +::: report.templatetags.report.order_queryset + options: + show_docstring_description: false + show_source: False + +!!! info "Provided QuerySet" + The provided queryset must be a valid Django queryset object, which is already available in the template context. + +#### Example + +In a report template which has a `PurchaseOrder` object available in its context as the variable `order`, return the matching line items ordered by part name: + +```html +{% raw %} +{% load report %} + +{% order_queryset order.lines.all 'part__name' as ordered_lines %} +``` + ### filter_queryset -The `filter_queryset` function allows for arbitrary filtering of the provided querysert. It takes a queryset and a list of filter arguments, and returns a filtered queryset. +The `filter_queryset` function allows for arbitrary filtering of the provided queryset. It takes a queryset and a list of filter arguments, and returns a filtered queryset. ::: report.templatetags.report.filter_queryset options: diff --git a/src/backend/InvenTree/report/templatetags/report.py b/src/backend/InvenTree/report/templatetags/report.py index f1542fad5e..8126c8d7d5 100644 --- a/src/backend/InvenTree/report/templatetags/report.py +++ b/src/backend/InvenTree/report/templatetags/report.py @@ -31,6 +31,25 @@ register = template.Library() logger = logging.getLogger('inventree') +@register.simple_tag() +def order_queryset(queryset: QuerySet, *args) -> QuerySet: + """Order a database queryset based on the provided arguments. + + Arguments: + queryset: The queryset to order + + Keyword Arguments: + field (str): Order the queryset based on the provided field + + Example: + {% order_queryset companies 'name' as ordered_companies %} + """ + if not isinstance(queryset, QuerySet): + return queryset + + return queryset.order_by(*args) + + @register.simple_tag() def filter_queryset(queryset: QuerySet, **kwargs) -> QuerySet: """Filter a database queryset based on the provided keyword arguments.