2.0 KiB
2.0 KiB
Django
Session.objects.filter(timestamp_start__year=2024)
JSON
{
"type": "session_start",
"operator": "equals",
"value": "2024"
}
HTML
<select name="filters">
<option value='[{"type": "session_start", "operator": "equals", "value": "2024"}]'>2024</option>
<option value='[{"type": "session_start", "operator": "equals", "value": "2023"}]'>2023</option>
</select>
Python: Python -> HTML
filters = [
{
"type": "session_start",
"operator": "equals",
"value": "2024"
}
]
# predefined values
session_start_select = Select(name="filters", children=session_start_options)
session_start_options = [
Option(value=create_filter("session_start", "equals", value=year))
for year in range(2000, 2024)
]
# user-selected values
Python: JSON -> Django
filter_types = {
"session_start": {
"equals": "timestamp_start__exact=",
"isnull": "timestamp_start__exact=None",
"greater_than": "timestamp_start__gt=",
"less_than": "timestamp_start__lt=",
},
}
# filter_string = request.GET.get("filters")
filter_string = """
{
"type": "session_start",
"operator": "equals",
"value": "2024"
}
"""
def string_to_django_filter_dict(s: str):
if s[-1] == "=":
s + value
key, value = s.split("=")
return {key: value}
filter_obj = json.loads(filter_string)[0]
field, operator, value = filter_obj
if type in filter_types:
if operator in filter_types[type]:
queryset.filter(Q(**string_to_django_filter_dict(filter_types[type][operator])}))
else:
return False
Python: Django -> JSON -> URI param
filters = [
{
"type": "session_start",
"operator": "equals",
"value": "2024"
}
]
context = {
"filters": json.dumps(filters)
}
return render("filter.html", context)
Python: Django -> JSON (function)
create_filter("session_start", "operator": "equals", "value": "2024")