This package adds some extra functionalities to graphene-django to facilitate the graphql use without Relay:
NOTE: Subscription support was moved to graphene-django-subscriptions.
For installing graphene-django-extras, just run this command in your shell:
pip install graphene-django-extras
Fields:
Mutations:
Types:
Paginations:
This is a basic example of graphene-django-extras package use. You can configure global paramsfor DjangoListObjectType classes pagination definitions on settings.py like this:
GRAPHENE_DJANGO_EXTRAS = {
'DEFAULT_PAGINATION_CLASS': 'graphene_django_extras.paginations.LimitOffsetGraphqlPagination',
'DEFAULT_PAGE_SIZE': 20,
'MAX_PAGE_SIZE': 50,
'CACHE_ACTIVE': True,
'CACHE_TIMEOUT': 300 # seconds
}
from django.contrib.auth.models import User
from graphene_django_extras import DjangoListObjectType, DjangoSerializerType, DjangoObjectType
from graphene_django_extras.paginations import LimitOffsetGraphqlPagination
from .serializers import UserSerializer
class UserType(DjangoObjectType):
class Meta:
model = User
description = " Type definition for a single user "
filter_fields = {
"id": ("exact", ),
"first_name": ("icontains", "iexact"),
"last_name": ("icontains", "iexact"),
"username": ("icontains", "iexact"),
"email": ("icontains", "iexact"),
"is_staff": ("exact", ),
}
class UserListType(DjangoListObjectType):
class Meta:
description = " Type definition for user list "
model = User
pagination = LimitOffsetGraphqlPagination(default_limit=25, ordering="-username") # ordering can be: string, tuple or list
class UserModelType(DjangoSerializerType):
""" With this type definition it't necessary a mutation definition for user's model """
class Meta:
description = " User model type definition "
serializer_class = UserSerializer
pagination = LimitOffsetGraphqlPagination(default_limit=25, ordering="-username") # ordering can be: string, tuple or list
filter_fields = {
"id": ("exact", ),
"first_name": ("icontains", "iexact"),
"last_name": ("icontains", "iexact"),
"username": ("icontains", "iexact"),
"email": ("icontains", "iexact"),
"is_staff": ("exact", ),
}
from graphene_django_extras import DjangoInputObjectType
class UserInput(DjangoInputObjectType):
class Meta:
description = " User InputType definition to use as input on an Arguments class on traditional Mutations "
model = User
import graphene
from graphene_django_extras import DjangoSerializerMutation
from .serializers import UserSerializer
from .types import UserType
from .input_types import UserInputType
class UserSerializerMutation(DjangoSerializerMutation):
"""
DjangoSerializerMutation auto implement Create, Delete and Update functions
"""
class Meta:
description = " DRF serializer based Mutation for Users "
serializer_class = UserSerializer
class UserMutation(graphene.Mutation):
"""
On traditional mutation classes definition you must implement the mutate function
"""
user = graphene.Field(UserType, required=False)
class Arguments:
new_user = graphene.Argument(UserInput)
class Meta:
description = " Graphene traditional mutation for Users "
@classmethod
def mutate(cls, root, info, *args, **kwargs):
...
import graphene
from graphene_django_extras import DjangoObjectField, DjangoListObjectField, DjangoFilterPaginateListField,
DjangoFilterListField, LimitOffsetGraphqlPagination
from .types import UserType, UserListType, UserModelType
from .mutations import UserMutation, UserSerializerMutation
class Queries(graphene.ObjectType):
# Possible User list queries definitions
users = DjangoListObjectField(UserListType, description='All Users query')
users1 = DjangoFilterPaginateListField(UserType, pagination=LimitOffsetGraphqlPagination())
users2 = DjangoFilterListField(UserType)
users3 = DjangoListObjectField(UserListType, filterset_class=UserFilter, description='All Users query')
# Defining a query for a single user
# The DjangoObjectField have a ID type input field, that allow filter by id and is't necessary to define resolve function
user = DjangoObjectField(UserType, description='Single User query')
# Another way to define a query to single user
user1 = UserListType.RetrieveField(description='User List with pagination and filtering')
# Exist two ways to define single or list user queries with DjangoSerializerType
user_retrieve1, user_list1 = UserModelType.QueryFields(
description='Some description message for both queries',
deprecation_reason='Some deprecation message for both queries'
)
user_retrieve2 = UserModelType.RetrieveField(
description='Some description message for retrieve query',
deprecation_reason='Some deprecation message for retrieve query'
)
user_list2 = UserModelType.ListField(
description='Some description message for list query',
deprecation_reason='Some deprecation message for list query'
)
class Mutations(graphene.ObjectType):
user_create = UserSerializerMutation.CreateField(deprecation_reason='Some one deprecation message')
user_delete = UserSerializerMutation.DeleteField()
user_update = UserSerializerMutation.UpdateField()
# Exist two ways to define mutations with DjangoSerializerType
user_create1, user_delete1, user_update1 = UserModelType.MutationFields(
description='Some description message for create, delete and update mutations',
deprecation_reason='Some deprecation message for create, delete and update mutations'
)
user_create2 = UserModelType.CreateField(description='Description message for create')
user_delete2 = UserModelType.DeleteField(description='Description message for delete')
user_update2 = UserModelType.UpdateField(description='Description message for update')
traditional_user_mutation = UserMutation.Field()
For use Directives you must follow two simple steps:
# settings.py
GRAPHENE = {
'SCHEMA_INDENT': 4,
'MIDDLEWARE': [
'graphene_django_extras.ExtraGraphQLDirectiveMiddleware'
]
}
# schema.py
from graphene_django_extras import all_directives
schema = graphene.Schema(
query=RootQuery,
mutation=RootMutation,
directives=all_directives
)
NOTE: Date directive depends on dateutil module, so if you do not have installed it, this directive will not beavailable. You can install dateutil module manually:
pip install python-dateutil
or like this:
pip install graphene-django-extras[date]
That's all !!!
{
allUsers(username_Icontains:"john"){
results(limit:5, offset:5){
id
username
firstName
lastName
}
totalCount
}
allUsers1(lastName_Iexact:"Doe", limit:5, offset:0){
id
username
firstName
lastName
}
allUsers2(firstName_Icontains: "J"){
id
username
firstName
lastName
}
user(id:2){
id
username
firstName
}
user1(id:2){
id
username
firstName
}
}
mutation{
userCreate(newUser:{username:"test", password:"test*123"}){
user{
id
username
firstName
lastName
}
ok
errors{
field
messages
}
}
userDelete(id:1){
ok
errors{
field
messages
}
}
userUpdate(newUser:{id:1, username:"John"}){
user{
id
username
}
ok
errors{
field
messages
}
}
}
Let's suppose that we have this query:
query{
allUsers{
result{
id
firstName
lastName
dateJoined
lastLogin
}
}
}
And return this data:
{
"data": {
"allUsers": {
"results": [
{
"id": "1",
"firstName": "JOHN",
"lastName": "",
"dateJoined": "2017-06-20 09:40:30",
"lastLogin": "2017-08-05 21:05:02"
},
{
"id": "2",
"firstName": "Golden",
"lastName": "GATE",
"dateJoined": "2017-01-02 20:36:45",
"lastLogin": "2017-06-20 10:15:31"
},
{
"id": "3",
"firstName": "Nike",
"lastName": "just do it!",
"dateJoined": "2017-08-30 16:05:20",
"lastLogin": "2017-12-05 09:23:09"
}
]
}
}
}
As we see, some data it's missing or just not have the format that we like it, so let's go to format the output datathat we desired:
query{
allUsers{
result{
id
firstName @capitalize
lastName @default(to: "Doe") @title_case
dateJoined @date(format: "DD MMM YYYY HH����SS")
lastLogin @date(format: "time ago")
}
}
}
And we get this output data:
{
"data": {
"allUsers": {
"results": [
{
"id": "1",
"firstName": "John",
"lastName": "Doe",
"dateJoined": "20 Jun 2017 09:40:30",
"lastLogin": "4 months, 12 days, 15 hours, 27 minutes and 58 seconds ago"
},
{
"id": "2",
"firstName": "Golden",
"lastName": "Gate",
"dateJoined": "02 Jan 2017 20:36:45",
"lastLogin": "5 months, 28 days, 2 hours, 17 minutes and 53 seconds ago"
},
{
"id": "3",
"firstName": "Nike",
"lastName": "Just Do It!",
"dateJoined": "30 Aug 2017 16:05:20",
"lastLogin": "13 days, 3 hours, 10 minutes and 31 seconds ago"
}
]
}
}
}
As we see, the directives are an easy way to format output data on queries, and it's can be put together like a chain.
List of possible date's tokens:"YYYY", "YY", "WW", "W", "DD", "DDDD", "d", "ddd", "dddd", "MM", "MMM", "MMMM", "HH", "hh", "mm", "ss", "A", "ZZ", "z".
You can use this shortcuts too:
1. Update dependencies
1. Upgrade to graphene v3
1. Upgrade graphene-django dependency to version == 2.6.0.
1. Upgrade graphql-core dependency to version >= 2.2.1.
2. Upgrade graphene dependency to version >= 2.1.8.
3. Upgrade graphene-django dependency to version >= 2.5.0.
4. Upgrade django-filter dependency to version >= 2.2.0.
5. Fixed bug 'DjangoSerializerOptions' object has no attribute 'interfaces' after update to graphene==2.1.8.
6. The tests were refactored and added some extra tests for DjangoSerializerType.
1. Fixed compatibilities issues to use graphene-django>=2.3.2.
2. Improved code quality and use Black code format.
3. Fixed minor bug with "time ago" date directive.
1. Improved DjangoListType and DjangoObjectType to share the filterset_class between the two class.
1. Improve DjangoSerializerMutation resolvers.
1. Fixed minor bug on ExtraGraphQLDirectiveMiddleware.
2. Fixed error with DRF 3.8 Compatibility.
3. Updated List's Fields to pass info.context to filterset as request, this allow filtering by request data.
4. Added new feature to ordering paginated queries.
1. Fixed minor bug on DjangoListObjectType.
1. Added filterset_class to the listing types as default filter.
2. Changed getOne by RetrieveField on DjangoListObjectType.
1. Added filterset_class to DjangoObjectType.
2. Fixed minor bug on factory_types function.
1. Fixed minor bug on *queryset_factory* function.
1. Updated Date directive format function for better string format combinations.
2. Updated custom Time, Date and DateTime base types to be used with Date directive.
3. Fixed bug with caching Introspection queries on ExtraGraphQLView.
1. Fixed bug with default Date directive format.
1. Added Binary graphql type. A BinaryArray is used to convert a Django BinaryField to the string form.
2. Added 'CACHE_ACTIVE' and 'CACHE_TIMEOUT' config options to GRAPHENE_DJANGO_EXTRAS settings for activate cache and
define a expire time. Default values are: CACHE_ACTIVE=False, CACHE_TIMEOUT=300 (seconds). Only available for
Queries.
3. Updated Date directive for use with Django TimeField, DateField, and DateTimeField.
4. Updated ExtraGraphQLView and AuthenticatedGraphQLView to allow use subscription requests on graphene-django >=2.0
5. Updated setup dependence to graphene-django>=2.0.
1. Fixed performance bug on some queries when request nested ManyToMany fields.
1. Fixed bug with default PaginationClass and DjangoFilterPaginateListField.
1. Added some useful directives to use on queries and fragments.
2. Fixed error on DjangoFilterPaginateListField resolve function.
1. Fixed bug on create and update function on serializer mutation.
1. Fixed minors bugs.
1. Added ok field and errors field to DjangoSerializerType like on DjangoSerializerMutation.
2. Added possibility of filtering in those queries fields that return a list of objects.
3. Updated DRF compatibility.
4. Fixed bug with filters when use global DEFAULT_PAGINATION_CLASS.
1. Fixed error with JSONField reference on Django==1.8.x installations.
1. Added DjangoSerializerType for quick Django's models types definition (See documentation).
2. Moved support for Subscriptions to graphene-django-subscriptions packages for
incompatibility with graphene-django>=2.0.
3. Fixed bug on DjangoFilterPaginateListField's pagination.
1. Added new settings param: MAX_PAGE_SIZE, to use on GRAPHENE_DJANGO_EXTRAS
configuration dict for better customize DjangoListObjectType's pagination.
2. Added support to Django's field: GenericRel.
3. Improve model's fields calculation for to add all possible related and reverse fields.
4. Improved documentation translation.
1. Improved ordering for showed fields on graphqli's IDE.
2. Added better descriptions for auto generated fields.
1. Improve converter.py file to avoid create field for auto generate OneToOneField
product of an inheritance.
2. Fixed bug in Emun generation for fields with choices of model inheritance child.
1. Fixed bug on GenericType and GenericInputType generations for
Queries list Type and Mutations.
1. Fixed with exclude fields and converter function.
1. Updated dependencies to graphene-django>=2.0.
2. Fixed minor bugs on queryset_builder performance.
1. Add queryset options to DjangoListObjectType Meta class for specify wanted model queryset.
2. Add AuthenticatedGraphQLView on graphene_django_extras.views for use
'permission', 'authorization' and 'throttle' classes based on the DRF settings. Special thanks to
[@jacobh](https://github.com/jacobh) for this
[comment](https://github.com/graphql-python/graphene/issues/249#issuecomment-300068390)
1. Fixed bug on subscriptions when not specified any field in "data" parameter to bean return on notification
message.
1. Fixed bug when subscribing to a given action (create, update or delete).
2. Added intuitive and simple web tool to test notifications of graphene-django-extras subscription.
1. Added support to multiselect choices values for models.CharField with choices attribute,
on queries and mutations. Example: Integration with django-multiselectfield package.
2. Added support to GenericForeignKey and GenericRelation fields, on queries and mutations.
3. Added first approach to support Subscriptions with Channels, with subscribe and unsubscribe operations.
Using channels-api package.
4. Fixed minors bugs.
1. Fix error on DateType encode.
1. Implement custom implementation of DateType for use converter and avoid error on Serializer Mutation.
1. Changed dependency of DRF to 3.6.4 on setup.py file, to avoid an import error produced by some changes in
new version of DRF=3.7.0 and because DRF 3.7.0 dropped support to Django versions < 1.10.
1. Fixed bug on DjangoInputObjectType class that refer to unused interface attribute.
2. Added support to create nested objects like in
[DRF](http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations),
it's valid to SerializerMutation and DjangoInputObjectType, only is necessary to specify nested_fields=True
on its Meta class definition.
3. Added support to show, only in mutations types to create objects and with debug=True on settings,
inputs autocomplete ordered by required fields first.
4. Fixed others minors bugs.
1. Make queries pagination configuration is more friendly.
1. Fixed a bug with input fields in the converter function.
1. Fixed bug in the queryset_factory function because it did not always return a queryset.
1. Remove hard dependence with psycopg2 module.
2. Fixed bug that prevented use queries with fragments.
3. Fixed bug relating to custom django_filters module and ordering fields.
1. Optimizing imports, fix some minors bugs and working on performance.
1. Repair conflict on converter.py, by the use of get_related_model function with: OneToOneRel,
ManyToManyRel and ManyToOneRel.
1. First commit.
https://docs.djangoproject.com/en/2.1/ref/models/relations/ RelatedManager 关系管理器用于 一对多、 多对多关系中。包括: ForeignKey关系的另外一端(即没有添加ForeignKey字段的model 一端可以使用关系管理器) class Question(models.Model): question_te
自己也是跟着别人的博客敲的出现的问题,这个是模板找不到路径。 在包含wsgi.py的同级目录中找到settings.py 然后在settings.py 找到这段代码: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [],
Graphene-Django A Django integration for Graphene. �� Join the community on Slack Documentation Visit the documentation to get started! Quickstart For installing graphene, just run this command in you
Graphene 项目的目的是使用非常性感的类型安全的 API 进行 Ajax 测试,是 Selenium 项目的扩展。
Please read UPGRADE-v2.0.mdto learn how to upgrade to Graphene 2.0. Graphene-SQLAlchemy A SQLAlchemy integration for Graphene. Installation For instaling graphene, just run this command in your shell
Graphene 是 Python 的 GraphQL 框架,用于快速轻松构建 GraphQL schemas/types 。支持多种数据源,包括 SQL(Django、SQLAlchemy)、NoSQL、自定义 Python 对象等等。 示例代码: import grapheneclass Query(graphene.ObjectType): hello = graphene.Strin
问题内容: 我在Django中有一些REST API端点,我想对Graphene使用相同的身份验证。该文档不提供任何指导。 问题答案: 例如,如果在API视图中使用,则可以将端点添加到以这种方式装饰的GraphQLView中: urls.py: 请注意,我们添加了一个新的端点,并保留了GraphiQL工具使用的原始端点。 然后,您应该在GraphQL客户端中设置标头并指向端点。 更新:请参阅此Gi
我有两种型号: 模式: GraphQL的目标之一是性能。为此,GraphQL必须通过GraphQL请求(例如:GraphiQL)仅向数据库请求所请求的字段 如果我请求以下查询: 石墨烯-django库生成以下SQL: 它得到了模型的所有字段!与API Rest问题相同,不符合GraphQL指南。 如果我从模型中请求字段,我希望查询是: 外键如何解决这个问题?