Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How should the table relationship be? #40

Open
ystekno opened this issue Mar 11, 2023 · 1 comment
Open

How should the table relationship be? #40

ystekno opened this issue Mar 11, 2023 · 1 comment

Comments

@ystekno
Copy link

ystekno commented Mar 11, 2023

class ProductGroup(pc.Model, table=True):
    code: str = None
    name: str


class Product(pc.Model, table=True):
    code: str = None
    name: str
    price = float
    image: str = None
    description: str = None
    is_active: bool = True
    productgroup: ProductGroup

The Product table is related to the ProductGroup table with a foreign key.
The above definition doesn't work!

@ystekno ystekno changed the title TypeError: 'module' object is not callable How should the table relationship be? Apr 5, 2023
@Avein
Copy link

Avein commented Sep 17, 2023

If you want to create a relationship in SQLmodel you need to specify a foreign key and optionally Relationship attributes. In you example it would be something like this

from sqlmodel import Relationship, Field


class ProductGroup(pc.Model, table=True):
    code: str = None
    name: str
    products: List['Product'] = Relationship(back_populates="product_group")



class Product(pc.Model, table=True):
    code: str = None
    name: str
    price = float
    image: str = None
    description: str = None
    is_active: bool = True
    product_group_id: Optional[int] = Field(default=None, foreign_key="productgroup.id"

    product_group: ["ProductGroup"] = Relationship(back_populates="products")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants