1

models.py

from typing import Optional
from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select, Column, VARCHAR

class User(SQLModel, table=True):
    __tablename__ = 'users'
    
    user_id: Optional[int] = Field(default=None, primary_key=True)
    first_name : str = Field(sa_column=Column("first_name", VARCHAR(54),nullable=False))
    last_name : str = Field(sa_column=Column("last_name", VARCHAR(54), nullable=True))
    email : str = Field(sa_column=Column("email", VARCHAR(54), unique=True, nullable=False))
    password : str = Field(sa_column=Column("password", VARCHAR(256), nullable=False))
    #role_id should be added as foreign key here

class Role(SQLModel, table=True):
    __tablename__ = 'roles'

    role_id: Optional[int] = Field(default=None, primary_key=True)
    name : str = Field(sa_column=Column("name", VARCHAR(54),nullable=False))
    

I have two models User and Role, here I want to add role_id as foreign key in User table. How can I achieve it in sqlmodel in fastapi

1
  • 3
    role_id: Optional[int] = Field(default=None, foreign_key='roles.role_id') would be my suggestion Commented Nov 7, 2022 at 9:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.