Title: async - can't access parent.child item (relationship models) using async · Issue #74 · fastapi/sqlmodel · GitHub
Open Graph Title: async - can't access parent.child item (relationship models) using async · Issue #74 · fastapi/sqlmodel
X Title: async - can't access parent.child item (relationship models) using async · Issue #74 · 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/74
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"async - can't access parent.child item (relationship models) using async","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\nDependencies: \r\naiosqlite\r\nhttps://pypi.org/project/aiosqlite/\r\n\r\n### Example Code\r\n\r\n```python\r\nimport asyncio\r\nfrom sqlmodel.ext.asyncio.session import AsyncSession\r\nfrom sqlalchemy.ext.asyncio import create_async_engine\r\nfrom typing import List, Optional\r\nfrom sqlmodel import Field, Relationship, SQLModel, select\r\n\r\n\r\nclass Team(SQLModel, table=True):\r\n id: Optional[int] = Field(default=None, primary_key=True)\r\n name: str\r\n headquarters: str\r\n\r\n heroes: List[\"Hero\"] = Relationship(back_populates=\"team\")\r\n\r\n\r\nclass Hero(SQLModel, table=True):\r\n id: Optional[int] = Field(default=None, primary_key=True)\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 team: Optional[Team] = Relationship(back_populates=\"heroes\")\r\n\r\n\r\nclass Item(SQLModel, table=True):\r\n id: Optional[int] = Field(default=None, primary_key=True)\r\n name: str\r\n\r\n\r\nsqlite_file_name = \"database.db\"\r\nsqlite_url = f\"sqlite+aiosqlite:///{sqlite_file_name}\"\r\n\r\nengine = create_async_engine(sqlite_url, echo=True)\r\n\r\n\r\nasync def create_db_and_tables():\r\n # SQLModel.metadata.create_all(engine)\r\n\r\n async with engine.begin() as conn:\r\n await conn.run_sync(SQLModel.metadata.drop_all)\r\n await conn.run_sync(SQLModel.metadata.create_all)\r\n\r\n\r\nasync def create_heroes():\r\n async with AsyncSession(engine) as session:\r\n team_preventers = Team(name=\"Preventers\", headquarters=\"Sharp Tower\")\r\n hero_deadpond = Hero(\r\n name=\"Deadpond\", secret_name=\"Dive Wilson\", team=team_preventers\r\n )\r\n\r\n session.add(hero_deadpond)\r\n await session.commit()\r\n await session.refresh(hero_deadpond)\r\n\r\n print(hero_deadpond)\r\n\r\n\r\nasync def select_heroes():\r\n async with AsyncSession(engine) as session:\r\n statement = select(Team).where(Team.name == \"Preventers\")\r\n result = await session.execute(statement)\r\n team_preventers = result.scalar()\r\n print(f\"Preventers team: {team_preventers}\")\r\n print(f\"Preventers heroes: {team_preventers.heroes}\")\r\n\r\n\r\nasync def main():\r\n await create_db_and_tables()\r\n await create_heroes()\r\n await select_heroes()\r\n\r\nif __name__ == \"__main__\":\r\n asyncio.run(main())\r\n\r\n```\r\n\r\n\r\n### Operating System\r\n\r\nmacOS\r\n\r\n### Operating System Details\r\n\r\nUsing a MacBook with macOS running FastAPI with docker.\r\n\r\n### SQLModel Version\r\n\r\n0.0.4\r\n\r\n### Python Version\r\n\r\n3.8.6\r\n\r\n### Additional Context\r\n\r\nWe have two models with a one to many relationship (Team -> Hero).\r\nUsing async / await AsyncSession , we are trying to access the parent's child ( {team_preventers.heroes} ) but this is causing the following exception : \r\n\r\n\r\nsqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s)\r\nsys:1: RuntimeWarning: coroutine 'Connection.cursor' was never awaited\r\n\r\n\u003cdetails>\r\n \u003csummary>Full stacktrace\u003c/summary>\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"async_test.py\", line 74, in \u003cmodule>\r\n asyncio.run(main())\r\n File \"/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/runners.py\", line 44, in run\r\n return loop.run_until_complete(main)\r\n File \"/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py\", line 642, in run_until_complete\r\n return future.result()\r\n File \"async_test.py\", line 71, in main\r\n await select_heroes()\r\n File \"async_test.py\", line 65, in select_heroes\r\n print(f\"Preventers heroes: {team_preventers.heroes}\")\r\n File \"/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py\", line 481, in __get__\r\n return self.impl.get(state, dict_)\r\n File \"/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py\", line 926, in get\r\n value = self._fire_loader_callables(state, key, passive)\r\n File \"/lib/python3.9/site-packages/sqlalchemy/orm/attributes.py\", line 962, in _fire_loader_callables\r\n return self.callable_(state, passive)\r\n File \"/lib/python3.9/site-packages/sqlalchemy/orm/strategies.py\", line 892, in _load_for_state\r\n return self._emit_lazyload(\r\n File \"/lib/python3.9/site-packages/sqlalchemy/orm/strategies.py\", line 1028, in _emit_lazyload\r\n result = session.execute(\r\n File \"/lib/python3.9/site-packages/sqlmodel/orm/session.py\", line 101, in execute\r\n return super().execute( # type: ignore\r\n File \"/lib/python3.9/site-packages/sqlalchemy/orm/session.py\", line 1689, in execute\r\n result = conn._execute_20(statement, params or {}, execution_options)\r\n File \"/lib/python3.9/site-packages/sqlalchemy/engine/base.py\", line 1583, in _execute_20\r\n return meth(self, args_10style, kwargs_10style, execution_options)\r\n File \"/lib/python3.9/site-packages/sqlalchemy/sql/elements.py\", line 323, in _execute_on_connection\r\n return connection._execute_clauseelement(\r\n File \"/lib/python3.9/site-packages/sqlalchemy/engine/base.py\", line 1452, in _execute_clauseelement\r\n ret = self._execute_context(\r\n File \"/lib/python3.9/site-packages/sqlalchemy/engine/base.py\", line 1814, in _execute_context\r\n self._handle_dbapi_exception(\r\n File \"/lib/python3.9/site-packages/sqlalchemy/engine/base.py\", line 1999, in _handle_dbapi_exception\r\n util.raise_(exc_info[1], with_traceback=exc_info[2])\r\n File \"/lib/python3.9/site-packages/sqlalchemy/util/compat.py\", line 207, in raise_\r\n raise exception\r\n File \"/lib/python3.9/site-packages/sqlalchemy/engine/base.py\", line 1771, in _execute_context\r\n self.dialect.do_execute(\r\n File \"/lib/python3.9/site-packages/sqlalchemy/engine/default.py\", line 717, in do_execute\r\n cursor.execute(statement, parameters)\r\n File \"/lib/python3.9/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py\", line 99, in execute\r\n self._adapt_connection._handle_exception(error)\r\n File \"/lib/python3.9/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py\", line 228, in _handle_exception\r\n raise error\r\n File \"/lib/python3.9/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py\", line 76, in execute\r\n _cursor = self.await_(self._connection.cursor())\r\n File \"/lib/python3.9/site-packages/sqlalchemy/util/_concurrency_py3k.py\", line 60, in await_only\r\n raise exc.MissingGreenlet(\r\nsqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s)\r\nsys:1: RuntimeWarning: coroutine 'Connection.cursor' was never awaited\r\n```\r\n\u003c/details>\r\n\r\n\r\n","author":{"url":"https://github.com/mnnweb","@type":"Person","name":"mnnweb"},"datePublished":"2021-09-02T09:56:20Z","url":"https://github.com/fastapi/sqlmodel/issues/74"}
| 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:6a3fd288-b01b-70db-6aae-37fbb0fac45c |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 9394:6A575:EE821:1530A2:6AFE14AF |
| html-safe-nonce | ec6a00082ba339dce62dfd7f39cfc6ad25f66293b36137a35c2f65f76bb3b3e7 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5Mzk0OjZBNTc1OkVFODIxOjE1MzBBMjo2QUZFMTRBRiIsInZpc2l0b3JfaWQiOiI2MjY2NzQwMDkyNzk5MTYxNTE5IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 1081093fd429328b8d9cd9ee1888723008d9011fdc2985b40c73f0971d216791 |
| hovercard-subject-tag | issue:986477711 |
| 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/74/issue_layout |
| twitter:image | https://opengraph.githubassets.com/3d7f3f3e13cf4a6f09228a2ff5c48a4e10443e734581760f5b9b81471e638882/fastapi/sqlmodel/issues/74 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/3d7f3f3e13cf4a6f09228a2ff5c48a4e10443e734581760f5b9b81471e638882/fastapi/sqlmodel/issues/74 |
| 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 | mnnweb |
| hostname | github.com |
| expected-hostname | github.com |
| None | 3cd8a1d79ccbf9aecac62781f79072482a49047fb982b8c9e2ad4aca8bf6a9af |
| 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 | 05539640a34afe6142a519483d78ddd766a1304a |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width