Skip to content

Commit 1e8a4b3

Browse files
authored
Example Union
1 parent d77d8e6 commit 1e8a4b3

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

docs/examples.rst

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
Schema Examples
2+
===========================
3+
4+
5+
Search all Models with Union
6+
-----------------
7+
8+
.. code:: python
9+
10+
class Book(SQLAlchemyObjectType):
11+
class Meta:
12+
model = BookModel
13+
interfaces = (relay.Node,)
14+
15+
16+
class Author(SQLAlchemyObjectType):
17+
class Meta:
18+
model = AuthorModel
19+
interfaces = (relay.Node,)
20+
21+
22+
class SearchResult(graphene.Union):
23+
class Meta:
24+
types = (Book, Author)
25+
26+
27+
class Query(graphene.ObjectType):
28+
node = relay.Node.Field()
29+
search = graphene.List(SearchResult, q=graphene.String()) # List field for search results
30+
31+
# Normal Fields
32+
all_books = SQLAlchemyConnectionField(Book)
33+
all_authors = SQLAlchemyConnectionField(Author)
34+
35+
def resolve_search(self, info, **args):
36+
q = args.get("q") # Search query
37+
38+
# Get queries
39+
bookdata_query = BookData.get_query(info)
40+
author_query = Author.get_query(info)
41+
42+
# Query Books
43+
books = bookdata_query.filter((BookModel.title.contains(q)) |
44+
(BookModel.isbn.contains(q)) |
45+
(BookModel.authors.any(AuthorModel.name.contains(q)))).all()
46+
47+
# Query Authors
48+
authors = author_query.filter(AuthorModel.name.contains(q)).all()
49+
50+
return authors + books # Combine lists
51+
52+
schema = graphene.Schema(query=Query, types=[Book, Author, SearchResult])
53+
54+
Example GraphQL query
55+
56+
.. code:: GraphQL
57+
58+
book(id: "Qm9vazow") {
59+
id
60+
title
61+
}
62+
search(q: "Making Games") {
63+
__typename
64+
... on Author {
65+
fname
66+
lname
67+
}
68+
... on Book {
69+
title
70+
isbn
71+
}
72+
}

0 commit comments

Comments
 (0)