dabapps / django-rest-framework-serialization-spec

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

Deal with when a model property/method call relies on underlying fields being loaded that are not mentioned in the serialization spec #2

Closed pmg103 closed 5 years ago

pmg103 commented 5 years ago
    serialization_spec = [
        'is_suspended',  # Needed by Activity.status
        'status',
        # ...
      ]

status needs is_suspended to be loaded so needs to be listed in the .only(). But we do not want to return that to the user. Maybe a plugin can help here:

class Requires(SerializationSpecPlugin):
    def __init__(self, fields):
        self.fields = fields
    def modify_queryset(self, queryset):
        # This the funky means by which an already-`.only()`d queryset can be extended with more fields
        existing, defer = queryset.query.deferred_loading
        existing_set = set(existing)
        existing_set.update(self.fields)
        queryset.query.deferred_loading = (frozenset(existing_set), defer)
        return queryset

    serialization_spec = [
        {'status': Requires(['is_suspended'])}
        # ...
      ]