8000 GitHub - graphql-python/graphene-sqlalchemy at d95dcc5e50595d1792b77a498233f6595d204a24
[go: up one dir, main page]

Skip to content
  • Insights
  • graphql-python/graphene-sqlalchemy

    Repository files navigation

    Version 3.0 is in beta stage. Please read #348 to learn about progress and changes in upcoming beta releases.


    Graphene Logo Graphene-SQLAlchemy

    Build Status PyPI version GitHub release (latest by date including pre-releases) codecov

    A SQLAlchemy integration for Graphene.

    Installation

    For installing Graphene, just run this command in your shell.

    pip install "graphene-sqlalchemy>=3"

    Examples

    Here is a simple SQLAlchemy model:

    from sqlalchemy import Column, Integer, String
    
    from sqlalchemy.ext.declarative import declarative_base
    
    Base = declarative_base()
    
    class UserModel(Base):
        __tablename__ = 'user'
        id = Column(Integer, primary_key=True)
        name = Column(String)
        last_name = Column(String)

    To create a GraphQL schema for it, you simply have to write the following:

    import graphene
    from graphene_sqlalchemy import SQLAlchemyObjectType
    
    class User(SQLAlchemyObjectType):
        class Meta:
            model = UserModel
            # use `only_fields` to only expose specific fields ie "name"
            # only_fields = ("name",)
            # use `exclude_fields` to exclude specific fields ie "last_name"
            # exclude_fields = ("last_name",)
    
    class Query(graphene.ObjectType):
        users = graphene.List(User)
    
        def resolve_users(self, info):
            query = User.get_query(info)  # SQLAlchemy query
            return query.all()
    
    schema = graphene.Schema(query=Query)

    Then you can simply query the schema:

    query = '''
        query {
          users {
            name,
            lastName
          }
        }
    '''
    result = schema.execute(query, context_value={'session': db_session})

    You may also subclass SQLAlchemyObjectType by providing abstract = True in your subclasses Meta:

    from graphene_sqlalchemy import SQLAlchemyObjectType
    
    class ActiveSQLAlchemyObjectType(SQLAlchemyObjectType):
        class Meta:
            abstract = True
    
        @classmethod
        def get_node(cls, info, id):
            return cls.get_query(info).filter(
                and_(cls._meta.model.deleted_at==None,
                     cls._meta.model.id==id)
                ).first()
    
    class User(ActiveSQLAlchemyObjectType):
        class Meta:
            model = UserModel
    
    class Query(graphene.ObjectType):
        users = graphene.List(User)
    
        def resolve_users(self, info):
            query = User.get_query(info)  # SQLAlchemy query
            return query.all()
    
    schema = graphene.Schema(query=Query)

    Full Examples

    To learn more check out the following examples:

    Contributing

    See CONTRIBUTING.md

    0