dabapps / django-rest-framework-serialization-spec

DEPRECATED, see https://github.com/dabapps/django-readers instead
MIT License
11 stars 0 forks source link

Plugin: Filter 1:M relations #26

Open pmg103 opened 4 years ago

pmg103 commented 4 years ago

Need a plugin to allow subqueries to be filtered. Something like:

serialization_spec = [
    {'reportgenerationbatch_set': Filter([
        'comparison_group',
        'report_templates',
    ], session=None)},

The filter would be any valid django filter as it would be applied to the inner queryset.

I'd prefer it if the filter (session=None in this case) appeared BEFORE the child serialization spec but kwargs must appear last in python. Could pass a dictionary as first arg?

NOTE: Do we need to use a new key, perhaps using to_attr, so that it doesnt clash with any other prefetches done anywhere else in the tree?

pmg103 commented 4 years ago

It could perhaps be done as a higher order function.

Usage would look like:

serialization_spec = [
    {'reportgenerationbatch_set': filter(session=None)([
        'comparison_group',
        'report_templates',
    ])},

Implementation would look like:

class Filter(SerializationSpecPlugin):
    def __init__(self, filter, serialization_spec):
        self.filter = self.filter
        self.serialization_spec = serialization_spec

    def modify_queryset(self, queryset):
        return queryset.filter(**self.filter)

    def get_value(self, instance):
        return getattr(instance, self.key)

def filter(**kwargs):
    return lambda spec: return Filter(kwargs, spec)
RealOrangeOne commented 4 years ago

Personally I think the API looks nicer as a class rather than HoF, as the HoF doesn't really gain anything.

RE to_attr, I don't think it matters? Assuming the entire serialization tree is SSM, it doesn't matter what they key is called, as it's only the library which will be using it.

pmg103 commented 4 years ago

Oh I can use Q-expressions of course:

serialization_spec = [
    {'reportgenerationbatch_set': Filtered(Q(session=None), [
        'comparison_group',
        'report_templates',
    ])},