Я изучаю FastAPI на YouTube, и когда мы соединяем таблицы с помощью sqlalchemy, я не получаю тот же результат, что и на видео. Видео выпущено 2 года назад, и я пытался найти решение, но ничего не добился.
Поэтому я пытаюсь присоединиться к POST таблица с таблицей голосов и подсчетом голосов для каждого POST, но я получаю общее количество голосов, но не объект сообщения, он просто показывает объект запроса.
Спасибо за заранее.
Модель
Код: Выделить всё
class Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, nullable=False)
content = Column(String, nullable=False)
published = Column(Boolean, server_default="TRUE")
created_at = Column(TIMESTAMP(timezone=True),
nullable=False, server_default=text('now()'))
owner_id = Column(Integer, ForeignKey(
"users.id", ondelete="CASCADE"), nullable=False)
owner = relationship("User")
class Vote(Base):
__tablename__ = "votes"
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
post_id = Column(Integer, ForeignKey("posts.id", ondelete="CASCADE"), primary_key=True)
created_at = Column(TIMESTAMP(timezone=True),
nullable=False, server_default=text('now()'))
Код: Выделить всё
@router.get("/posts")
async def get_posts(
db: Session = Depends(get_db),
current_user: int = Depends(oauth2.get_current_user),
search: Optional[str] = '',
):
posts = db.query(models.Post).filter(models.Post.title.contains(search)).all()
results = db.query(models.Post, func.count(models.Vote.post_id).label("votes_count")).\
join(models.Vote, models.Vote.post_id == models.Post.id, isouter=True).\
group_by(models.Post.id).all()
print(results)
return results
Код: Выделить всё
[(, 0), (, 0), (, 1), (, 0), (, 0)]
Это ошибка, когда я возвращаю результаты.< /p>
Код: Выделить всё
INFO: 127.0.0.1:50202 - "GET /posts HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 322, in jsonable_encoder
data = dict(obj)
^^^^^^^^^
TypeError: cannot convert dictionary update sequence element #0 to a sequence
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 327, in jsonable_encoder
data = vars(obj)
^^^^^^^^^
TypeError: vars() argument must have __dict__ attribute
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py", line 426, in run_asgi
result = await app( # type: ignore[func-returns-value]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__
return await self.app(scope, receive, send)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/applications.py", line 1106, in __call__
await super().__call__(scope, receive, send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/applications.py", line 122, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 184, in __call__
raise exc
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 79, in __call__
raise exc
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 68, in __call__
await self.app(scope, receive, sender)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py", line 20, in __call__
raise e
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py", line 17, in __call__
await self.app(scope, receive, send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/routing.py", line 718, in __call__
await route.handle(scope, receive, send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/routing.py", line 276, in handle
await self.app(scope, receive, send)
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/starlette/routing.py", line 66, in app
response = await func(request)
^^^^^^^^^^^^^^^^^^^
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/routing.py", line 292, in app
content = await serialize_response(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/routing.py", line 180, in serialize_response
return jsonable_encoder(response_content)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 301, in jsonable_encoder
jsonable_encoder(
File "/home/eminent/Documents/My codes/FastAPI/Tutorials/SocialAPI/venv/lib/python3.11/site-packages/fastapi/encoders.py", line 330, in jsonable_encoder
raise ValueError(errors) from e
ValueError: [TypeError('cannot convert dictionary update sequence element #0 to a sequence'), TypeError('vars() argument must have __dict__ attribute')]
Источник: https://stackoverflow.com/questions/781 ... ry-objects