liveBook · Manning

One-to-many relationship

As explained in Build Financial Software with Generative AI (From Scratch)

A one-to-many relationship is a data relationship in which one record can be associated with multiple records of another type.

A one-to-many relationship lets one company have multiple related records, such as addresses or phone numbers. Represent those related rows as arrays in the returned data model. section 10.4

Implement the relationship by:

  • Defining addresses and phones as lists on CompanyDetailRecord. section 10.4
  • Joining the company with related tables; multiple related records produce multiple result rows. section 10.4
  • Grouping rows in Python or aggregating related records with a PostgreSQL CTE. section 10.4

Company details

A company with two addresses and three phone numbers can produce five joined rows. Convert those rows into one company object containing separate address and phone arrays. section 10.4

Listing 10.23 The CompanyDetailRecord field
class CompanyDetailRecord(BaseModel):
    company_id: Optional[UUID4] = Field(
        None,
        title="Company ID",
        description="Unique identifier for the company.",
    )
    name: Optional[str] = Field(
        None,
        title="Name",
        description="Name of the company.",
        max_length=255,
    )
…
    addresses: Optional[list[Address]] = Field( #1
        None,                    #1
        title="Addresses",  #1
        description="List of Addresses.",  #1
    )  #1
    phones: Optional[list[Phone]] = Field( #2
        None,  #2
        title="Phones",  #2
        description="List of Phone Numbers.",  #2
    )  #2

Inspect the response-model fields that store related addresses and phone numbers. section 10.4

How Build Financial Software with Generative AI (From Scratch) covers it

How deep it goes
Explains list modeling, joined-row multiplication, Python grouping, and PostgreSQL aggregation alternatives.
Examples
Uses company addresses and phone numbers, including a two-address and three-phone joined-result example.
What you can do after
Build a company-detail response with related records grouped into address and phone arrays.
How it connects
Connects Pydantic models, SQL joins, Python row processing, PostgreSQL CTEs, and JSON aggregation.

Also explained in

Compare how 12 books explain one-to-many relationship →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Financial Software with Generative AI (From Scratch). The section links point to the parts of the book it draws on.