Open Luferov opened 2 years ago
I think there is no way to implement a simple yet flexible API for this feature. The proposed API will work fine only for simple cases. But, for example this approach does not cover search by initials - 'Иванов И. И.' instead of 'Иванов Иван Иванович'. Possible solutions:
query SearchUser($search: String!) {
users(
filter: {
cross: [
{
template: '{last_name} {first_name[0].} {sir_name[0].}'
icontains: $search
}
]
}
) {
edges {
node {
id
last_name
first_name
sir_name
}
}
}
}
from graphene_django_filter import AdavancedDjangoObjectType
class UserType(AdavancedDjangoObjectType): class Meta: model = User fields = 'all' cross_search = { 'full_name: { 'template': '{last_name} {first_name[0].} {sir_name[0].}' 'lookups: ('exact', 'icontains',) } }
```graphql
query SearchUser($search: String!) {
users(
filter: {
full_name: { icontains: $search }
}
) {
edges {
node {
id
last_name
first_name
sir_name
}
}
}
}
import django_filters
from graphene_django_filter import AdavancedFilterSet
class UserFilterSet(AdvancedFilterSet): full_name = django_filters.CharFilter(field_name='full_name', lookup_expr='exact') full_name__icontains = django_filters.CharFilter(field_name='full_name', lookup_expr='icontains')
def filter_queryset(self, queryset): return super().filter_queryset( queryset.annotate(full_name=...) )
I think the third approach looks fine and will cover most cases. In the most complex cases, you can always use the fourth one.
Sometimes, it is required to search for one variable in several fields. For example:
Graphql query might look like this:
Graphql query should generate sql query via django orm like this: