我需要使用 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

据我所知,sql 查询应该是这样的:

  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 (将#修改为@)