dabapps / django-rest-framework-serialization-spec

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

Optimise away unused prefetches #34

Closed pmg103 closed 4 years ago

pmg103 commented 4 years ago

When an intermediate relation is only mentioned in order to prefetch a nested relation, then the intermediate prefetch can be skipped entirely.

Eg:

    serialization_spec = [
        {'users': [
            {'activity_product_version_sessions': [
                {'activity_product_version': [
                    {'product_version': [
                        {'product': [
                            'id',
                            'name'
                        ]}
                    ]}
                ]}
            ]}
        ]}
    ]

can be reduced down to just

Organisation.objects.prefetch_related(
  Prefetch(
    'users__activity_product_version_sessions__activity_product_version__product_version__product',
    queryset=Product.objects.only('id', 'name')
  )
)

althought what about the reverse FKs to stitch the whole lot back together again? 🤔

pmg103 commented 4 years ago

ALTHOUGH -- it looks like it does all the intermediate prefetches anyway. So I dont think this "optimisation" would gain anything anyway