Title: FastAPI and Pydantic - Relationships Not Working · Issue #37 · fastapi/sqlmodel · GitHub
Open Graph Title: FastAPI and Pydantic - Relationships Not Working · Issue #37 · fastapi/sqlmodel
X Title: FastAPI and Pydantic - Relationships Not Working · Issue #37 · fastapi/sqlmodel
Description: First Check I added a very descriptive title to this issue. I used the GitHub search to find a similar issue and didn't find it. I searched the SQLModel documentation, with the integrated search. I already searched in Google "How to X in...
Open Graph Description: First Check I added a very descriptive title to this issue. I used the GitHub search to find a similar issue and didn't find it. I searched the SQLModel documentation, with the integrated search. I...
X Description: First Check I added a very descriptive title to this issue. I used the GitHub search to find a similar issue and didn't find it. I searched the SQLModel documentation, with the integrated searc...
Opengraph URL: https://github.com/fastapi/sqlmodel/issues/37
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"FastAPI and Pydantic - Relationships Not Working","articleBody":"### First Check\r\n\r\n- [X] I added a very descriptive title to this issue.\r\n- [X] I used the GitHub search to find a similar issue and didn't find it.\r\n- [X] I searched the SQLModel documentation, with the integrated search.\r\n- [X] I already searched in Google \"How to X in SQLModel\" and didn't find any information.\r\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\r\n- [X] I already checked if it is not related to SQLModel but to [Pydantic](https://github.com/samuelcolvin/pydantic).\r\n- [X] I already checked if it is not related to SQLModel but to [SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy).\r\n\r\n### Commit to Help\r\n\r\n- [X] I commit to help with one of those options 👆\r\n\r\n### Example Code\r\n\r\n```python\r\nfrom typing import List, Optional\r\n\r\nfrom fastapi import Depends, FastAPI, HTTPException, Query\r\nfrom sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select\r\n\r\n\r\nclass TeamBase(SQLModel):\r\n name: str\r\n headquarters: str\r\n\r\n\r\nclass Team(TeamBase, table=True):\r\n id: Optional[int] = Field(default=None, primary_key=True)\r\n\r\n heroes: List[\"Hero\"] = Relationship(back_populates=\"team\")\r\n\r\n\r\nclass TeamCreate(TeamBase):\r\n pass\r\n\r\n\r\nclass TeamRead(TeamBase):\r\n id: int\r\n\r\n\r\nclass TeamUpdate(SQLModel):\r\n id: Optional[int] = None\r\n name: Optional[str] = None\r\n headquarters: Optional[str] = None\r\n\r\n\r\nclass HeroBase(SQLModel):\r\n name: str\r\n secret_name: str\r\n age: Optional[int] = None\r\n\r\n team_id: Optional[int] = Field(default=None, foreign_key=\"team.id\")\r\n\r\n\r\nclass Hero(HeroBase, table=True):\r\n id: Optional[int] = Field(default=None, primary_key=True)\r\n\r\n team: Optional[Team] = Relationship(back_populates=\"heroes\")\r\n\r\n\r\nclass HeroRead(HeroBase):\r\n id: int\r\n\r\n\r\nclass HeroCreate(HeroBase):\r\n pass\r\n\r\n\r\nclass HeroUpdate(SQLModel):\r\n name: Optional[str] = None\r\n secret_name: Optional[str] = None\r\n age: Optional[int] = None\r\n team_id: Optional[int] = None\r\n\r\n\r\nclass HeroReadWithTeam(HeroRead):\r\n team: Optional[TeamRead] = None\r\n\r\n\r\nclass TeamReadWithHeroes(TeamRead):\r\n heroes: List[HeroRead] = []\r\n\r\n\r\nsqlite_file_name = \"database.db\"\r\nsqlite_url = f\"sqlite:///{sqlite_file_name}\"\r\n\r\nconnect_args = {\"check_same_thread\": False}\r\nengine = create_engine(sqlite_url, echo=True, connect_args=connect_args)\r\n\r\n\r\ndef create_db_and_tables():\r\n SQLModel.metadata.create_all(engine)\r\n\r\n\r\ndef get_session():\r\n with Session(engine) as session:\r\n yield session\r\n\r\n\r\napp = FastAPI()\r\n\r\n\r\n@app.on_event(\"startup\")\r\ndef on_startup():\r\n create_db_and_tables()\r\n\r\n\r\n@app.post(\"/heroes/\", response_model=HeroRead)\r\ndef create_hero(*, session: Session = Depends(get_session), hero: HeroCreate):\r\n db_hero = Hero.from_orm(hero)\r\n session.add(db_hero)\r\n session.commit()\r\n session.refresh(db_hero)\r\n return db_hero\r\n\r\n\r\n@app.get(\"/heroes/\", response_model=List[HeroRead])\r\ndef read_heroes(\r\n *,\r\n session: Session = Depends(get_session),\r\n offset: int = 0,\r\n limit: int = Query(default=100, lte=100),\r\n):\r\n heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()\r\n return heroes\r\n\r\n\r\n@app.get(\"/heroes/{hero_id}\", response_model=HeroReadWithTeam)\r\ndef read_hero(*, session: Session = Depends(get_session), hero_id: int):\r\n hero = session.get(Hero, hero_id)\r\n if not hero:\r\n raise HTTPException(status_code=404, detail=\"Hero not found\")\r\n return hero\r\n\r\n\r\n@app.patch(\"/heroes/{hero_id}\", response_model=HeroRead)\r\ndef update_hero(\r\n *, session: Session = Depends(get_session), hero_id: int, hero: HeroUpdate\r\n):\r\n db_hero = session.get(Hero, hero_id)\r\n if not db_hero:\r\n raise HTTPException(status_code=404, detail=\"Hero not found\")\r\n hero_data = hero.dict(exclude_unset=True)\r\n for key, value in hero_data.items():\r\n setattr(db_hero, key, value)\r\n session.add(db_hero)\r\n session.commit()\r\n session.refresh(db_hero)\r\n return db_hero\r\n\r\n\r\n@app.delete(\"/heroes/{hero_id}\")\r\ndef delete_hero(*, session: Session = Depends(get_session), hero_id: int):\r\n\r\n hero = session.get(Hero, hero_id)\r\n if not hero:\r\n raise HTTPException(status_code=404, detail=\"Hero not found\")\r\n session.delete(hero)\r\n session.commit()\r\n return {\"ok\": True}\r\n\r\n\r\n@app.post(\"/teams/\", response_model=TeamRead)\r\ndef create_team(*, session: Session = Depends(get_session), team: TeamCreate):\r\n db_team = Team.from_orm(team)\r\n session.add(db_team)\r\n session.commit()\r\n session.refresh(db_team)\r\n return db_team\r\n\r\n\r\n@app.get(\"/teams/\", response_model=List[TeamRead])\r\ndef read_teams(\r\n *,\r\n session: Session = Depends(get_session),\r\n offset: int = 0,\r\n limit: int = Query(default=100, lte=100),\r\n):\r\n teams = session.exec(select(Team).offset(offset).limit(limit)).all()\r\n return teams\r\n\r\n\r\n@app.get(\"/teams/{team_id}\", response_model=TeamReadWithHeroes)\r\ndef read_team(*, team_id: int, session: Session = Depends(get_session)):\r\n team = session.get(Team, team_id)\r\n if not team:\r\n raise HTTPException(status_code=404, detail=\"Team not found\")\r\n return team\r\n\r\n\r\n@app.patch(\"/teams/{team_id}\", response_model=TeamRead)\r\ndef update_team(\r\n *,\r\n session: Session = Depends(get_session),\r\n team_id: int,\r\n team: TeamUpdate,\r\n):\r\n db_team = session.get(Team, team_id)\r\n if not db_team:\r\n raise HTTPException(status_code=404, detail=\"Team not found\")\r\n team_data = team.dict(exclude_unset=True)\r\n for key, value in team_data.items():\r\n setattr(db_team, key, value)\r\n session.add(db_team)\r\n session.commit()\r\n session.refresh(db_team)\r\n return db_team\r\n\r\n\r\n@app.delete(\"/teams/{team_id}\")\r\ndef delete_team(*, session: Session = Depends(get_session), team_id: int):\r\n team = session.get(Team, team_id)\r\n if not team:\r\n raise HTTPException(status_code=404, detail=\"Team not found\")\r\n session.delete(team)\r\n session.commit()\r\n return {\"ok\": True}\r\n```\r\n\r\n\r\n### Description\r\n\r\nIs realationships working for anyone?\r\nI either get null or an empty list.\r\n\r\nOK, so, I've copied the last full file preview at the - https://sqlmodel.tiangolo.com/tutorial/fastapi/relationships/\r\nRun it and it creates the Db and the foreign key\r\nThen I've insert the data into the Db.\r\n\r\nChecking the docs UI everything looks great\r\n\u003cimg width=\"1368\" alt=\"Screenshot 2021-08-26 at 23 33 55\" src=\"https://user-images.githubusercontent.com/11464425/131044799-26f45765-95bf-4528-8353-4277dcfceb3e.png\">\r\n\r\nBut when I do a request for a hero, `team` is `null`\r\n\u003cimg width=\"1400\" alt=\"Screenshot 2021-08-26 at 23 36 39\" src=\"https://user-images.githubusercontent.com/11464425/131044990-e773fe1f-3b3a-48e4-9204-74ce0b14718c.png\">\r\n\r\nReally not sure what going on, especially when all I have just is copied the code example with no changes?\r\n\r\n### Operating System\r\n\r\nLinux\r\n\r\n### Operating System Details\r\n\r\n_No response_\r\n\r\n### SQLModel Version\r\n\r\n0.0.4\r\n\r\n### Python Version\r\n\r\n3.8.2\r\n\r\n### Additional Context\r\n\r\n_No response_","author":{"url":"https://github.com/Chunkford","@type":"Person","name":"Chunkford"},"datePublished":"2021-08-26T22:40:52Z","url":"https://github.com/fastapi/sqlmodel/issues/37"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:40bce206-13d9-2ddb-2e5c-e5e9bcb564f3 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | B04A:12FD69:3055C:42176:6AFE0F54 |
| html-safe-nonce | e40dbd1d828758287bed976bc27ee0e947c3ed72950d9481d995e8ecc420a1ab |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCMDRBOjEyRkQ2OTozMDU1Qzo0MjE3Njo2QUZFMEY1NCIsInZpc2l0b3JfaWQiOiI4MTg5MzA3NzY2Nzc1MzUzMTcyIiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 291190c77a2c752a56af31971694b691d3d7fde1fe42ecf0c0b04f44e79135dd |
| hovercard-subject-tag | issue:980700795 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/fastapi/sqlmodel/37/issue_layout |
| twitter:image | https://opengraph.githubassets.com/36433e07a7fbae3a2268aa91238c797617649856002adb474fca4c395ca1ddc0/fastapi/sqlmodel/issues/37 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/36433e07a7fbae3a2268aa91238c797617649856002adb474fca4c395ca1ddc0/fastapi/sqlmodel/issues/37 |
| og:image:alt | First Check I added a very descriptive title to this issue. I used the GitHub search to find a similar issue and didn't find it. I searched the SQLModel documentation, with the integrated search. I... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | Chunkford |
| hostname | github.com |
| expected-hostname | github.com |
| None | 1fd4053be37b4bd545b4f38f1cecad058c343776acf2cbc6806316f26270e55e |
| turbo-cache-control | no-preview |
| go-import | github.com/fastapi/sqlmodel git https://github.com/fastapi/sqlmodel.git |
| octolytics-dimension-user_id | 156354296 |
| octolytics-dimension-user_login | fastapi |
| octolytics-dimension-repository_id | 399495186 |
| octolytics-dimension-repository_nwo | fastapi/sqlmodel |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 399495186 |
| octolytics-dimension-repository_network_root_nwo | fastapi/sqlmodel |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 635a57b3d0df6bc21c0f39fc7078888fb90e4066 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width