如何解决我需要使用 SQLAlchemy 和 Graphene 编写查询
我需要从数据库中获取作者并计算每个作者的书数。当我在 FastAPI + graphene + sqlalchemy bundle 中执行 GraphQLAPI 时,我无法理解使用 sqlalchemy 构建查询的语法
class Books(sqlAlchemyObjectType):
class Meta:
model = BookModel
class Authors(sqlAlchemyObjectType):
class Meta:
model = AuthorModel
class LibraryQuery(graphene.ObjectType):
books = graphene.List(Books)
authors = graphene.List(Authors)
def resolve_authors(self,info,**kwargs):
authors_query = Authors.get_query(info)
return authors_query
def resolve_search_authors(self,**kwargs):
name = kwargs.get("name")
authors_query = Authors.get_query(info)
authors = authors_query.filter((AuthorModel.name.contains(name))).all()
return authors
SELECT
a.name,COUNT(*) as number_of_books
FROM
author a
JOIN book_author ba ON a.id = ba.author_id
GROUP BY
a.name
ORDER BY number_of_books DESC
还有models.py
:
association_table = Table('book_author',Base.Metadata,Column('book_id',Integer,ForeignKey('book.id')),Column('author_id',ForeignKey('author.id')))
class Book(Base):
__tablename__ = "book"
id = Column(Integer,primary_key=True)
title = Column(String)
published = Column(Date)
author = relationship("Author",secondary=association_table,back_populates="book")
class Author(Base):
__tablename__ = "author"
id = Column(Integer,primary_key=True)
name = Column(String)
book = relationship("Book",back_populates="author")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。