【问题标题】:How to get models schema (type_defs) in form of string?如何以字符串的形式获取模型模式(type_defs)?
【发布时间】:2021-11-28 03:26:47
【问题描述】:

示例代码

我有以下型号。

class Post(Base):
    __tablename__ = "post"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String)
    author = Column(String)
    content = Column(String)
    time_created = Column(DateTime(timezone=True), server_default=func.now())

使用此架构

class PostSchema(SQLAlchemyObjectType):
    class Meta:
        model = Post

问题

如何以这样的字符串形式获取 graphql 模式定义

"""
type Post{
id: ID
title: string!
author: String!
content: String!
time_created: Int!
}
"""
  • 我试过这个,但没有type_defs 选项。
  • graphene.Field(PostModel).type_defs

【问题讨论】:

    标签: graphene-python


    【解决方案1】:

    您可以使用的一个选项是内省您的架构,而不仅仅是对象类型。假设您有一个名为schema 的石墨烯架构,

    from graphene_sqlalchemy import SQLAlchemyObjectType
    class schema(SQLAlchemyObjectType):
        class Meta:
            model = MyModel
    

    你可以这样做:

    schema_dict = schema.introspect()
    

    这将返回你的模式的字典版本,你想要的类型可以在这里找到:

    types = schema_dict["__schema"]["types"]
    

    不幸的是,这会返回所有对象类型的列表,因此您可能需要对其进行处理以缩小您想要的范围,例如:

    list(filter(lambda types: types['name'] == 'PostSchema', types))
    

    另一种方式

    def make_schemas(model):
        d = """
            """
        for i, key in model.__table__.columns.items():
    
            x = str(key.type.python_type)
            x = x.replace("<class '", '')
            x = x.replace("'>", '')
            x = x.title()
            if x in ['Str', 'Datetime.Datetime']:
                x = 'String'
            if x == 'Bool':
                x = 'Boolean'
            d += f"""
                    {i}: {x}
                    """
        y = f"""
        type {model.__tablename__.title()} {{
        {d}
        }}
        """
        return y
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      • 2012-12-19
      • 2015-10-23
      相关资源
      最近更新 更多