2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-06-16 12:05:53 +00:00

Add new report filters for accessing database tables (#8560)

* Add new report filters for accessing database tables

* Simplify

* Handle exception

* Add docs

* Update docstrings
This commit is contained in:
Oliver
2024-11-27 07:51:27 +11:00
committed by GitHub
parent 368f3b7bd4
commit 20fb1250f8
2 changed files with 118 additions and 0 deletions

View File

@ -8,8 +8,10 @@ from decimal import Decimal
from typing import Any, Optional
from django import template
from django.apps.registry import apps
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.models.query import QuerySet
from django.utils.safestring import SafeString, mark_safe
from django.utils.translation import gettext_lazy as _
@ -29,6 +31,50 @@ register = template.Library()
logger = logging.getLogger('inventree')
@register.simple_tag()
def filter_queryset(queryset: QuerySet, **kwargs) -> QuerySet:
"""Filter a database queryset based on the provided keyword arguments.
Arguments:
queryset: The queryset to filter
Keyword Arguments:
field (any): Filter the queryset based on the provided field
Example:
{% filter_queryset companies is_supplier=True as suppliers %}
"""
return queryset.filter(**kwargs)
@register.simple_tag()
def filter_db_model(model_name: str, **kwargs) -> QuerySet:
"""Filter a database model based on the provided keyword arguments.
Arguments:
model_name: The name of the Django model - including app name (e.g. 'part.partcategory')
Keyword Arguments:
field (any): Filter the queryset based on the provided field
Example:
{% filter_db_model 'part.partcategory' is_template=True as template_parts %}
"""
app_name, model_name = model_name.split('.')
try:
model = apps.get_model(app_name, model_name)
except Exception:
return None
if model is None:
return None
queryset = model.objects.all()
return filter_queryset(queryset, **kwargs)
@register.simple_tag()
def getindex(container: list, index: int) -> Any:
"""Return the value contained at the specified index of the list.