dabapps / django-readers

A lightweight function-oriented toolkit for better organisation of business logic and efficient selection and projection of data in Django projects.

Home Page:https://www.django-readers.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is limiting relationships possible?

adammsteele opened this issue · comments

Hi,

Just trying to get my head around what is and isn't supported, the use case I'm after would be something like an Author with many Books, and writing a spec to show the author and the top 5 books by some ordering criteria.

I tried a couple of approaches to no avail:

  • I wrote a slice pair which used QuerySet.__getitem__ to mimic slicing, but I think that won't work in general if there are other filters to be applied to the overall queryset
  • An annotation using row_number also did not work because one cannot filter on a window function

Let me know if you would prefer questions to be asked on a different platform.

Thanks for the library.

Hi! Thanks for trying out django-readers 😎

I think the question isn't really readers-specific: readers just uses prefetch_related to load relationships, so what you need to be able to do is prefetch a limited number of objects. This article suggests a few ways to do it, involving OuterRef and Subquery. If you can get this to work with "just" your queryset (ie without readers) then it should be fairly straightforward to convert this into a reader pair.

I'll leave this ticket open because I'm very interested to hear how you get on!