tips.rst @9e4d3603-ee4d-41ca-bf91-64b039611ccf/main — view markup · raw · history · blame
Tips
Querying
In order to make querying against the database work, there are two alternatives:
- Set the db session when you do the execution:
schema = graphene.Schema() schema.execute(context_value={'session': session})
- Create a query for the models.
Base = declarative_base() Base.query = db_session.query_property() class MyModel(Base): # ...
If you don't specify any, the following error will be displayed:
A query in the model Base or a session in the schema is required for querying.
Sorting
By default the SQLAlchemyConnectionField sorts the result elements over the primary key(s). The query has a sort argument which allows to sort over a different column(s)
Given the model
class Pet(Base): __tablename__ = 'pets' id = Column(Integer(), primary_key=True) name = Column(String(30)) pet_kind = Column(Enum('cat', 'dog', name='pet_kind'), nullable=False) class PetNode(SQLAlchemyObjectType): class Meta: model = Pet class PetConnection(Connection): class Meta: node = PetNode class Query(ObjectType): allPets = SQLAlchemyConnectionField(PetConnection)
some of the allowed queries are
- Sort in ascending order over the name column
allPets(sort: name_asc){ edges { node { name } } }
- Sort in descending order over the per_kind column and in ascending order over the name column
allPets(sort: [pet_kind_desc, name_asc]) { edges { node { name petKind } } }