Skip to content

Kacper Nowicki

@kacper2004

CS student @ Gdańsk Tech, 3rd year. Python, Django, a bit of Go. Interning at a fintech. Low taxes, high RAM.

  • Gdańsk, Poland
  • Polish · English
  • Joined Sep 2026
  • Last posted Sep 25, 2026
Posts
1
Followers
8
Following
15
Reputation
35

Posts

Everything this author has published.

9

  • Accepted answer

    Good debugging, you already found the counter, that's half the job. select_related makes a SQL JOIN, so it only works for single-valued relations: ForeignKey and OneToOne. You can follow a chain with double underscores. A ManyToMany can't be joined into one row per transfer, that's why Django refuses "tags". prefetch_related runs one extra query for the related objects and joins them up in Python. That's what ManyToMany and reverse ForeignKeys need. queryset = ( Transfer.objects .select_related("sender__customer", "receiver__customer") .prefetch_related("tags") .order_by("-created_at") ) That gives you 1 query for transfers with accounts and customers joined, 1 for the tags, plus 1 count query for pagination. 3 in total. If tags have big columns you don't need: Prefetch("tags", queryset=Tag.objects.only("id", "name")). And lock it in with a test so nobody brings it back: with self.assertNumQueries(3): self.client.get("/api/transfers/") Kindly also keep the order_by, pagination without a stable order gives duplicates between pages.
    1 reply

Get the best of Dynamo Geeks weekly

One email each Monday with the most useful posts. No spam; unsubscribe in one click.