Replies: 2 comments 2 replies
-
@waldner I think you need a reverse foreign key lookup in that case. For now you need to make two queries. from piccolo.columns.reference import LazyTableReference
from piccolo.columns.reverse_lookup import ReverseLookup
class PiccoloPieces(Table, tablename="pieces"):
# unchanged columns
parts = ReverseLookup(
LazyTableReference("PiccoloParts", module_path=__name__), reverse_fk="piece_id"
) After that you can query the piece_with_parts = await PiccoloPieces.select(
PiccoloPieces.all_columns(),
PiccoloPieces.parts(), # reverse lookup
).where(PiccoloPieces.id == 1) The result is this and you get all the [
{
"id": 1,
"type": "Type A",
"description": "Desc Type A",
"start_date": datetime.date(2025, 4, 12),
"timezone": "UTC",
"internal_id": "1",
"parts": [
{
"id": 1,
"piece_id": 1,
"description": "Piccolo Part 1",
"start_date": datetime.date(2025, 4, 12),
"internal_id": "100",
}
],
}
] |
Beta Was this translation helpful? Give feedback.
-
As an extra info, if using the
to restore the correct structure of the piece schema.
which produces no error but doesn't rename the part dictionary either. This makes the kind of postprocessing described above more complicated than it should be, because in the case of a piece with no parts, |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I have the following schemas:
So there's a one-to many relationship between pieces.id and parts. Now to get a piece with all its parts, I'm currently forced to use a query like this:
This looks backwards to me, first because I'm interested in pieces yet I have to specify everyting in function of
PiccoloParts
in the query to traverse the foreign key, second because if I have a piece with no associated parts, I'd still like to get that as a result, while the above query returns an empty list. So in plain SQL terms I'd do:But I'm unable to obtain the same result with piccolo. Am I missing something here?
The ultimate goal is to build a pydantic object
PieceWithParts
with the following structure:where the
parts
list might be empty if no associated parts are found.Would querying
pieces
alone for the piece first, then (if the piece is found) queryingparts
for all parts matching the piece id be a better (although slightly less efficient and/or idiomatic) way to accomplish the task?Beta Was this translation helpful? Give feedback.
All reactions