Skip to content

Union of SQLAlchemy connections and simple objects #369

@jmartinhoj

Description

@jmartinhoj

I need a query to return either a list of SQLAlchemy objects (via a connection) or an error message. Here's the code:

from models import Users
from graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField
import graphene

class User(SQLAlchemyObjectType):
    class Meta:
        model = Users #SQLAlchemy model
        interfaces = (graphene.relay.Node,)

class Message(graphene.ObjectType):
    message = graphene.String()

class UserResults(graphene.ObjectType):
    users = SQLAlchemyConnectionField(User.connection)

class UnionUsers(graphene.Union):
    class Meta:
        types = (UserResults, Message)

    @classmethod
    def resolve_type(cls, instance, info):
        if(type(instance) is list):
            return UserResults
        return Message

class Query(graphene.ObjectType):
    users = graphene.Field(type=UnionUsers)

    def resolve_all_users(self, info, **kwargs):
        if('''condition'''):
            return Message(message="asd")
        query = User.get_query(info)
        return query.filter_by(email = "foo@foo.foo").all()

When the ''''condition''' is met and a Message is returned, it works well. Unfortunately, otherwise, when a list of Users is returned, the list of users that is returned in graphql is the complete list of all users, no matter the filter in the query. Is this a bug or should I do it differently?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions