Search code examples
pythonsqlalchemyormfastapi

FastAPI relationship between two tables


I'm new to fastAPI and still learning. I was making two tables which is UserApp and Family, with model and schemas as below:

Model:

# AppUser
class AppUser(Base):
    __tablename__ = 'Users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    email = Column(String)
    password = Column(String)
    birth = Column(Integer)
    age = Column(Integer)
    gender = Column(String)
    quest_role = Column(Boolean)
    family_id = Column(Integer, ForeignKey('Families.id'))
    last_login = Column(DateTime)
    createdAt = Column(DateTime)
    updatedAt = Column(DateTime)
    publishedAt = Column(DateTime)

    family = relationship("Family", back_populates="users")

# Families
class Family(Base):
    __tablename__ = 'Families'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    createdAt = Column(DateTime)
    updatedAt = Column(DateTime)

    users = relationship("AppUser", back_populates="family")

Schemas.py:

# =================================Family===========================================
# Create Family Schema (Pydantic Model)
class FamilyCreate(BaseModel):
    name: str
    users: int

# Complete Family Schema (Pydantic Model)
class Family(BaseModel):
    id: int
    name: str
    createdAt: datetime = None
    updatedAt: datetime = None

    class Config:
        orm_mode = True

# =================================App_User=========================================== 
# Create appUser Schema (Pydantic Model)
class AppUserCreate(BaseModel):
    name: str
    email: str
    password: str
    birth: int
    age: int
    gender: str
    quest_role: bool

# Complete appUser Schema (Pydantic Model)
class AppUser(BaseModel):
    id: int
    name: str
    email: str
    password: str
    birth: int
    age: int
    gender: str
    quest_role: bool
    family_id: List[Family] = None
    last_login: datetime = None
    createdAt: datetime = None
    updatedAt: datetime = None
    publishedAt: datetime = None

    class Config:
        orm_mode = True

Output:


  {
    "id": 1,
    "name": "string",
    "email": "string",
    "password": "string",
    "birth": 0,
    "age": 0,
    "gender": "string",
    "quest_role": true,
    "family_id": null,
    "last_login": "2023-06-23T14:10:34.120964",
    "createdAt": "2023-06-23T14:10:34.120964",
    "updatedAt": "2023-06-23T14:10:34.120964",
    "publishedAt": "2023-06-23T14:10:34.120964"
  }
]

I'm trying to make family_id not null and expecting to give me a lists from family table.

Expected Output:

[
  {
    "id": 0,
    "name": "string",
    "email": "string",
    "password": "string",
    "birth": 0,
    "age": 0,
    "gender": "string",
    "quest_role": true,
    "family_id": [
      {
        "id": 0,
        "name": "string",
        "createdAt": "2023-06-23T06:56:22.730Z",
        "updatedAt": "2023-06-23T06:56:22.730Z"
      }
    ],
    "last_login": "2023-06-23T06:56:22.730Z",
    "createdAt": "2023-06-23T06:56:22.730Z",
    "updatedAt": "2023-06-23T06:56:22.730Z",
    "publishedAt": "2023-06-23T06:56:22.730Z"
  }
]

I have tried checking other StackOverflow questions for a solution but I was not able to find a solution or get alot of information to my issue.

Any help with this would be appreciated and if I haven't provided enough information, I am more than willing to provide more.


Solution

  • Change you AppUser to following

    class AppUser(BaseModel):
        id: int
        name: str
        email: str
        password: str
        birth: int
        age: int
        gender: str
        quest_role: bool
        family_id: int
        family : Family
        last_login: datetime = None
        createdAt: datetime = None
        updatedAt: datetime = None
        publishedAt: datetime = None
    
        class Config:
            orm_mode = True
    
    

    Output will be :

    [
      {
        "id": 0,
        "name": "string",
        "email": "string",
        "password": "string",
        "birth": 0,
        "age": 0,
        "gender": "string",
        "quest_role": true,
        "family_id": <id>,
        "family": [
          {
            
            "name": "string",
            "createdAt": "2023-06-23T06:56:22.730Z",
            "updatedAt": "2023-06-23T06:56:22.730Z"
          }
        ],
        "last_login": "2023-06-23T06:56:22.730Z",
        "createdAt": "2023-06-23T06:56:22.730Z",
        "updatedAt": "2023-06-23T06:56:22.730Z",
        "publishedAt": "2023-06-23T06:56:22.730Z"
      }
    ]
    

    Hope this helps!