Skip to content

Optimize pk-based hyperlinked relationships. #1872

@Archelyst

Description

@Archelyst

Maybe I'm doing something wrong here. When I ask my application for a list of objects (e.g. /my-objects/) it makes 2 initial database queries (one for the count and one for the list). Then during serialization - using hyperlinked serialization - for each related field on each object another query is fired. So I easily end up with more than 200 database queries for a simple list - that's just unacceptable.

Looking into the code it's clear what causes this: in order to create the hyperlinks to the related objects, those objects must be loaded (often the same object is loaded 100 times). So my assumption is that the described behavior is not caused by misconfiguration but by design.

I created a kind of hacky solution which uses the my_related_object_id property to generate the url for my_related_object without loading the object (of which only the id is used anyway). Is that valid? Shouldn't this be something that's done by drf? It seems to work, haven't had any problems so far.

Even when this is solved the combination with nested routes is a whole new adventure, but that's out of the scope of this project / ticket :)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions