dabapps / django-rest-framework-serialization-spec

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

Properly merge the serialization_specs required by SerializationSpecPlugins #41

Open pmg103 opened 4 years ago

pmg103 commented 4 years ago

Currently if a plugin fetches some data it needs and the main serialization_spec also fetches that data, then if you don't alias the name you get errors if the querysets don't perfectly match, or you have to alias.

Ideally SSM would analyse your plugins hierarchy and merge the specs together ensuring the superset of all required data was fetched, even though only that specified in the view would actually be returned. Viz:

class MyActivityRatersSubmitted(SerializationSpecPlugin):
    def get_serialization_spec(self):
        return [
            {'self_users': Filtered('users', Q(user=self.request_user), [
                'id',
                'raters_submitted'
            ])}
        ]

    def get_value(self, instance):
        return len(instance.self_users) > 0 and instance.self_users[0].raters_submitted

class MyActivityIsRespondent(SerializationSpecPlugin):
    def get_serialization_spec(self):
        return [
            {'self_users': Filtered('users', Q(user=self.request_user), [
                'id',
            ])}
        ]

    def get_value(self, instance):
        return len(instance.self_users) > 0

class MyActivityList(SerializationSpecMixin, generics.ListAPIView):
    queryset = Activity.objects.all()

    serialization_spec = [
        'id',
        {'is_respondent': MyActivityIsRespondent()},
        {'raters_submitted': MyActivityRatersSubmitted()},
    ]

It might also be worth dictating that

  1. if you want the original relation you must use the name of that relation
  2. if you want a filtered version you must give it a name
  3. if you reuse the same name then the filter must be identical: if it is not SSM should error

This would assist in merging the trees together

pmg103 commented 3 years ago

Was this resolved by https://github.com/dabapps/django-rest-framework-serialization-spec/pull/44 ?