Database *functions* run inside PostgreSQL, not in Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | # ====================================================================== # Database *functions* run inside PostgreSQL, not in Python. `annotate()` adds a # computed column to every row: `Concat` joins values (SQL `||`), `Upper` upper- # cases, `Length` counts characters, and `Round(field, n)` rounds to n decimals. # `values_list()` then returns plain tuples instead of model instances. # ====================================================================== # ---------------------------------------------------------------------- # annotated books # ---------------------------------------------------------------------- # Django: Book.objects.annotate( label=Concat(Upper("title"), Value(" by "), "author__name"), title_len=Length("title"), price_rounded=Round("price", 0), ).values_list("label", "title_len", "price_rounded") # SQL: # SELECT (COALESCE(UPPER("examples_book"."title"), '') || COALESCE((COALESCE(' by ', '') || COALESCE("examples_author"."name", '')), '')) AS "label", LENGTH("examples_book"."title") AS "title_len", ROUND("examples_book"."price", 0) AS "price_rounded" # FROM "examples_book" # INNER JOIN "examples_author" ON ("examples_book"."author_id" = "examples_author"."id") # Result: # HARRY POTTER by J. K. Rowling (len=12, ~$20) # THE HOBBIT by J. R. R. Tolkien (len=10, ~$15) # THE LORD OF THE RINGS by J. R. R. Tolkien (len=21, ~$29) # POSTGRES FOR AUTHORS by Karl Müller (len=20, ~$0) |