项目作者: art1415926535

项目描述 :
Filters for Graphene SQLAlchemy integration
高级语言: Python
项目地址: git://github.com/art1415926535/graphene-sqlalchemy-filter.git
创建时间: 2019-08-05T03:09:46Z
项目社区:https://github.com/art1415926535/graphene-sqlalchemy-filter

开源协议:MIT License

下载


Graphene-SQLAlchemy-Filter

CI Coverage Status PyPI version

Filters for Graphene SQLAlchemy integration

preview

Quick start

Create a filter and add it to the graphene field.

  1. from graphene_sqlalchemy_filter import FilterableConnectionField, FilterSet
  2. class UserFilter(FilterSet):
  3. is_admin = graphene.Boolean()
  4. class Meta:
  5. model = User
  6. fields = {
  7. 'username': ['eq', 'ne', 'in', 'ilike'],
  8. 'is_active': [...], # shortcut!
  9. }
  10. @staticmethod
  11. def is_admin_filter(info, query, value):
  12. if value:
  13. return User.username == 'admin'
  14. else:
  15. return User.username != 'admin'
  16. class Query(ObjectType):
  17. all_users = FilterableConnectionField(UserConnection, filters=UserFilter())

Now, we’re going to create query.

  1. {
  2. allUsers (
  3. filters: {
  4. isActive: true,
  5. or: [
  6. {isAdmin: true},
  7. {usernameIn: ["moderator", "cool guy"]}
  8. ]
  9. }
  10. ){
  11. edges {
  12. node {
  13. id
  14. username
  15. }
  16. }
  17. }
  18. }

Filters

FilterSet class must inherit graphene_sqlalchemy_filter.FilterSet or your subclass of this class.

There are three types of filters:

  1. automatically generated filters
  2. simple filters
  3. filters that require join

Automatically generated filters

  1. class UserFilter(FilterSet):
  2. class Meta:
  3. model = User
  4. fields = {
  5. 'username': ['eq', 'ne', 'in', 'ilike'],
  6. 'is_active': [...], # shortcut!
  7. }

Metaclass must contain the sqlalchemy model and fields.

Automatically generated filters must be specified by fields variable.
Key - field name of sqlalchemy model, value - list of expressions (or shortcut).

Shortcut (default: [...]) will add all the allowed filters for this type of sqlalchemy field (does not work with hybrid property).

Key Description GraphQL postfix
eq equal
ne not equal Ne
like like Like
ilike insensitive like Ilike
is_null is null IsNull
in in In
not_in not in NotIn
lt less than Lt
lte less than or equal Lte
gt greater than Gt
gte greater than or equal Gte
range in range Range
contains contains (PostgreSQL array) Contains
contained_by contained_by (PostgreSQL array) ContainedBy
overlap overlap (PostgreSQL array) Overlap

Simple filters

  1. class UserFilter(FilterSet):
  2. is_admin = graphene.Boolean()
  3. @staticmethod
  4. def is_admin_filter(info, query, value):
  5. if value:
  6. return User.username == 'admin'
  7. else:
  8. return User.username != 'admin'

Each simple filter has a class variable that passes to GraphQL schema as an input type and function <field_name>_filter that makes filtration.

The filtration function takes the following arguments:

  • info - ResolveInfo graphene object
  • query - sqlalchemy query (not used in that filters type)
  • value - the value of a filter

The return value can be any type of sqlalchemy clause. This means that you can return not_(and_(or_(...), ...)).

Metaclass is not required if you do not need automatically generated filters.

Filters that require join

This type of filter is the same as simple filters but has a different return type.

The filtration function should return a new sqlalchemy query and clause (like simple filters).

  1. class UserFilter(FilterSet):
  2. is_moderator = graphene.Boolean()
  3. @classmethod
  4. def is_moderator_filter(cls, info, query, value):
  5. membership = cls.aliased(query, Membership, name='is_moderator')
  6. query = query.outerjoin(
  7. membership,
  8. and_(
  9. User.id == membership.user_id,
  10. membership.is_moderator.is_(True),
  11. ),
  12. )
  13. if value:
  14. filter_ = membership.id.isnot(None)
  15. else:
  16. filter_ = membership.id.is_(None)
  17. return query, filter_

Model aliases

The function cls.aliased(query, model, name='...') returns sqlalchemy alias from the query. It has one differing parameter - query (SQLAlchemy Query object). Other arguments are the same as sqlalchemy.orm.aliased.

Identical joins will be skipped by sqlalchemy.

Changed in version 1.7: The first parameter is now a query.

Features

Filter registration and nested fields filters

Filters can be registered for each SQLAlchemy model in a subclass of FilterableConnectionField.

Register your filters by inheriting FilterableConnectionField and setting filters (key - SQLAlchemy model, value - FilterSet object).

  1. class CustomField(FilterableConnectionField):
  2. filters = {
  3. User: UserFilter(),
  4. }

Overriding SQLAlchemyObjectType.connection_field_factory allows you to generate nested connections with filters.

  1. class UserNode(SQLAlchemyObjectType):
  2. class Meta:
  3. model = User
  4. interfaces = (Node,)
  5. connection_field_factory = CustomField.factory

Important:

  1. pagination (first/after, last/before) are performed by python (keep this in mind when working with large amounts of data)
  2. nested filters work by dataloaders
  3. this module optimizes one-to-many relationships, to optimize many-to-one relationships use sqlalchemy_bulk_lazy_loader
  4. nested filters require graphene_sqlalchemy>=2.1.2

Example

  1. # Filters
  2. class UserFilter(FilterSet):
  3. class Meta:
  4. model = User
  5. fields = {'is_active': [...]}
  6. class CustomField(FilterableConnectionField):
  7. filters = {
  8. User: UserFilter(),
  9. }
  10. # Nodes
  11. class UserNode(SQLAlchemyObjectType):
  12. class Meta:
  13. model = User
  14. interfaces = (Node,)
  15. connection_field_factory = CustomField.factory
  16. class GroupNode(SQLAlchemyObjectType):
  17. class Meta:
  18. model = Group
  19. interfaces = (Node,)
  20. connection_field_factory = CustomField.factory
  21. # Connections
  22. class UserConnection(Connection):
  23. class Meta:
  24. node = UserNode
  25. class GroupConnection(Connection):
  26. class Meta:
  27. node = GroupNode
  28. # Query
  29. class Query(ObjectType):
  30. all_users = CustomField(UserConnection)
  31. all_groups = CustomField(GroupConnection)
  1. {
  2. allUsers (filters: {isActive: true}){
  3. edges { node { id } }
  4. }
  5. allGroups {
  6. edges {
  7. node {
  8. users (filters: {isActive: true}) {
  9. edges { node { id } }
  10. }
  11. }
  12. }
  13. }
  14. }

Rename GraphQL filter field

  1. class CustomField(FilterableConnectionField):
  2. filter_arg = 'where'
  3. class Query(ObjectType):
  4. all_users = CustomField(UserConnection, where=UserFilter())
  5. all_groups = FilterableConnectionField(GroupConnection, filters=GroupFilter())
  1. {
  2. allUsers (where: {isActive: true}){
  3. edges { node { id } }
  4. }
  5. allGroups (filters: {nameIn: ["python", "development"]}){
  6. edges { node { id } }
  7. }
  8. }

Rename expression

  1. class BaseFilter(FilterSet):
  2. GRAPHQL_EXPRESSION_NAMES = dict(
  3. FilterSet.GRAPHQL_EXPRESSION_NAMES,
  4. **{'eq': 'equal', 'not': 'i_never_asked_for_this'}
  5. )
  6. class Meta:
  7. abstract = True
  8. class UserFilter(BaseFilter):
  9. class Meta:
  10. model = User
  11. fields = {'first_name': ['eq'], 'last_name': ['eq']}
  1. {
  2. allUsers (filters: {iNeverAskedForThis: {firstNameEqual: "Adam", lastNameEqual: "Jensen"}}){
  3. edges { node { id } }
  4. }
  5. }

Custom shortcut value

  1. class BaseFilter(FilterSet):
  2. ALL = '__all__'
  3. class Meta:
  4. abstract = True
  5. class UserFilter(BaseFilter):
  6. class Meta:
  7. model = User
  8. fields = {'username': '__all__'}

Localization of documentation

  1. class BaseFilter(FilterSet):
  2. DESCRIPTIONS = {
  3. 'eq': 'Полностью совпадает.',
  4. 'ne': 'Не совпадает.',
  5. 'like': 'Регистрозависимая проверка строки по шлабону.',
  6. 'ilike': 'Регистронезависимая проверка строки по шлабону.',
  7. 'regexp': 'Регистрозависимая проверка строки по регулярному выражению.',
  8. 'is_null': 'Равно ли значение `null`. Принемает `true` или `false`.',
  9. 'in': 'Проверка вхождения в список.',
  10. 'not_in': 'Проверка не вхождения в список.',
  11. 'lt': 'Меньше, чем указанное значение.',
  12. 'lte': 'Меньше или равно указанному значению.',
  13. 'gt': 'Больше, чем указанное значение.',
  14. 'gte': 'Больше или равно указанному значению.',
  15. 'range': 'Значение входит в диапазон значений.',
  16. 'and': 'Объединение фильтров с помощью ``AND``.',
  17. 'or': 'Объединение фильтров с помощью ``OR``.',
  18. 'not': 'Отрицание указанных фильтров.',
  19. }
  20. class Meta:
  21. abstract = True

Custom expression

  1. def today_filter(field, value: bool):
  2. today = func.date(field) == date.today()
  3. return today if value else not_(today)
  4. class BaseFilter(FilterSet):
  5. # Add expression.
  6. TODAY = 'today'
  7. EXTRA_EXPRESSIONS = {
  8. 'today': {
  9. # Add the name of the expression in GraphQL.
  10. 'graphql_name': 'today',
  11. # Update allowed filters (used by shortcut).
  12. 'for_types': [types.Date, types.DateTime],
  13. # Add a filtering function (takes the sqlalchemy field and value).
  14. 'filter': today_filter,
  15. # Add the GraphQL input type. Column type by default.
  16. 'input_type': (
  17. lambda type_, nullable, doc: graphene.Boolean(nullable=False)
  18. ),
  19. # Description for the GraphQL schema.
  20. 'description': 'It is today.',
  21. }
  22. }
  23. class Meta:
  24. abstract = True
  25. class PostFilter(BaseFilter):
  26. class Meta:
  27. model = Post
  28. fields = {'created': ['today'], 'updated': [...]}
  1. {
  2. allPosts (filters: {createdToday: false, updatedToday: true}){
  3. edges { node { id } }
  4. }
  5. }

Custom column types

ALLOWED_FILTERS and EXTRA_ALLOWED_FILTERS only affect shortcut.

If you do not use the shortcut, you can skip the next steps described in the section.

  1. class MyString(types.String):
  2. pass
  3. class BaseFilter(FilterSet):
  4. # You can override all allowed filters
  5. # ALLOWED_FILTERS = {types.Integer: ['eq']}
  6. # Or add new column type
  7. EXTRA_ALLOWED_FILTERS = {MyString: ['eq']}
  8. class Meta:
  9. abstract = True