Skip to content

Instantly share code, notes, and snippets.

@mfonism
Created December 3, 2019 12:31
Show Gist options
  • Save mfonism/68903ea852348b90807b1c9139958c10 to your computer and use it in GitHub Desktop.
Save mfonism/68903ea852348b90807b1c9139958c10 to your computer and use it in GitHub Desktop.
class QueryParamReader:
class Meta:
model = Event
grouping_params = [
"day",
"device_type",
"category",
"client",
"client_group",
"valid",
]
ordering_params = utils.ascify_descify(sorting_fields)
filtering_params = grouping_fields
query_delimiter = " "
#####################################################################
class QueryParamReader:
class Meta:
model = Event
query_delimiter = " "
group_by = GroupingParam(
restrict_to=[
"day",
"device_type",
"category",
"client",
"client_group",
"valid",
]
)
order_by = OrderingParam(
restrict_to=utils.ascify_descify(
["day", "device_type", "category", "client", "client_group", "valid"]
)
)
# the filtering param class
# deduces the type of the param value from the field on the model
# and may take a list of allowed values (restrict_to) for the param
# you may also specify whether it is to accept only one (singular) value
# or appropriately delimited multiple values
# it accepts multiple values by default
clients = FilteringParam("client")
client_groups = FilteringParam("client_group")
device_types = FilteringParam("device_type", restrict_to=Event.DEVICE_TYPE_CHOICES)
categories = FilteringParam("category")
valid = FilteringParam("valid", singular=True)
# would have to write a 'date' transform for the following to work
start_date = FilteringParam("timestamp", singular=True, filter_op="date__gte")
end_date = FilteringParam("timestamp", singular=True, filter_op="date__lte")
def __init__(self, *args, **kwargs):
# prepare all params
# ensure the same thing isn't specified in meta and outside meta
# ensure params are in line with existing fields on specified model
pass
def read(self, request, queryset, *args, **kwargs):
# read the query params
# return an appropriately modified queryset
# ex.
# return (queryset
# .filter(
# Q(valid=True),
# Q(timestamp__date__gte=2018-09-04),
# Q(category=864) | Q(category=141) | Q(category=308)
# )
# .values('client', 'category', 'device_type')
# .order_by('client', '-device_type')
# )
pass
def full_clean(self, params_dict, *args, **kwargs):
# params_dict is a map of all read parameters and their values
# this is where you can do things like
# making sure the values of one parameter are a subset of
# the values of some other parameter
# you can even modify parameter values here
# make sure to return the resulting params_dict
return params_dict
class Param:
pass
class FilteringParam(Param):
pass
class GroupingParam(Param):
pass
class OrderingParam(Param):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment