All Projects → topletal → django-model-mutations

topletal / django-model-mutations

Licence: MIT license
Graphene Django mutations for Django models made easier

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to django-model-mutations

graphene-django-cud
Easy and painless CUD-mutations for graphene-django.
Stars: ✭ 66 (+186.96%)
Mutual labels:  graphene, graphene-django
graphene django crud
Turns the django ORM into a graphql API
Stars: ✭ 23 (+0%)
Mutual labels:  graphene, graphene-django
djaq
Django queries
Stars: ✭ 54 (+134.78%)
Mutual labels:  django-models
graphene-elastic
Graphene Elasticsearch/OpenSearch (DSL) integration
Stars: ✭ 68 (+195.65%)
Mutual labels:  graphene
fastapi-debug-toolbar
A debug toolbar for FastAPI.
Stars: ✭ 90 (+291.3%)
Mutual labels:  graphene
jakartaee-faces-sample
Jakarta EE 10 Faces Example
Stars: ✭ 20 (-13.04%)
Mutual labels:  graphene
wagtail-graphql
App to automatically add GraphQL support to a Wagtail website
Stars: ✭ 37 (+60.87%)
Mutual labels:  graphene
fastql
⚙️ Full stack, Modern Web Application Generator. ✨ Using FastAPI, GraphQL, PostgreSQL as database, Docker, automatic HTTPS and more. 🔖
Stars: ✭ 80 (+247.83%)
Mutual labels:  graphene
django-paranoid-model
Django abstract model with paranoid behavior
Stars: ✭ 17 (-26.09%)
Mutual labels:  django-models
travel-expense-manager
A travel expense manager made with Django, GraphQL, Next.js and Tailwind CSS
Stars: ✭ 20 (-13.04%)
Mutual labels:  graphene-django
Flask-GraphQL-Graphene-MySQL-Docker-StarterKit
Reference Repository for the article
Stars: ✭ 28 (+21.74%)
Mutual labels:  graphene
gql-next
A Python GraphQL Client library providing ability to validate and make type-safe GraphQL calls
Stars: ✭ 74 (+221.74%)
Mutual labels:  graphene
CourseCake
By serving course 📚 data that is more "edible" 🍰 for developers, we hope CourseCake offers a smooth approach to build useful tools for students.
Stars: ✭ 21 (-8.7%)
Mutual labels:  graphene
gtk-rs-core
Rust bindings for GNOME libraries
Stars: ✭ 179 (+678.26%)
Mutual labels:  graphene
sanic-graphql-example
Sanic using Graphsql + SQLAlchemy example
Stars: ✭ 21 (-8.7%)
Mutual labels:  graphene
graphene-sqlalchemy-filter
Filters for Graphene SQLAlchemy integration
Stars: ✭ 117 (+408.7%)
Mutual labels:  graphene
graphenize
A cli tool to auto-generate Graphene model from json data
Stars: ✭ 12 (-47.83%)
Mutual labels:  graphene
gxchain-wallet
GXC Wallet for mobile
Stars: ✭ 69 (+200%)
Mutual labels:  graphene
django-graphql-geojson
GeoJSON support for Graphene Django
Stars: ✭ 61 (+165.22%)
Mutual labels:  graphene
flask-graphql-neo4j
A simple flask API to test-drive GraphQL and Neo4j
Stars: ✭ 74 (+221.74%)
Mutual labels:  graphene

Django Model Mutations

build status PyPI version

This package adds Mutation classes that make creating graphene mutations with django models easier using Django Rest Framework serializers. It extends graphene Mutation class in a similar way to Django Rest Framework views or original Django views.

It also provides easy way to add permissions checks or ensure logged-in user, as well as easy way to override or add funcionality similar to django forms or rest framework views - such as get_queryset() or save() functions.

There is also advanced error reporting from rest framework, that returns non-valid fields and error messages.

Inspired by Saleor, graphene-django-extras and django-rest-framework

Installation

pip install django-model-mutations

Basic Usage

Main classes that this package provides:

mutations mixins
CreateModelMutation LoginRequiredMutationMixin
CreateBulkModelMutation
UpdateModelMutation
UpdateBulkModelMutation
DeleteModelMutation
DeleteBulkModelMutation

Django usage

Input type (Arguments) is generated from serializer fields
Return type is retrieved by model from global graphene registry, you just have to import it as in example

from django_model_mutations import mutations, mixins
from your_app.types import UserType  # important to import types to register in global registry
from your_app.serializers import UserSerializer


# Create Mutations
# use mixins.LoginRequiredMutationMixin to ensure only logged-in user can perform this mutation
# MAKE SURE this mixin is FIRST in inheritance order
class UserCreateMutation(mixins.LoginRequiredMutationMixin, mutations.CreateModelMutation):
    class Meta:
        serializer_class = UserSerializer
        # OPTIONAL META FIELDS:
        permissions = ('your_app.user_permission',) # OPTIONAL: specify user permissions
        lookup_field = 'publicId'  # OPTIONAL: specify database lookup column, default is 'id' or 'ids'
        return_field_name = 'myUser' # OPTIONAL: specify return field name, default is model name
        input_field_name = 'myUser' # OPTIONAL: specify input field name, defauls is 'input'
        

class UserBulkCreateMutation(mutations.CreateBulkModelMutation):
    class Meta:
        serializer_class = UserSerializer


# Update Mutations
class UserUpdateMutation(mutations.UpdateModelMutation):
    class Meta:
        serializer_class = UserSerializer

# WARNING: Bulk update DOES NOT USE serializer, due to limitations of rest framework serializer. 
# Instead specify model and argument fields by yourself.
class UserBulkUpdateMutation(mutations.UpdateBulkModelMutation):
    class Arguments:
        is_active = graphene.Boolean()

    class Meta:
        model = User

# Delete Mutations
# delete mutations doesn't use serializers, as there is no need
class UserDeleteMutation(mutations.DeleteModelMutation):
    class Meta:
        model = User

class UserBulkDeleteMutation(mutations.DeleteBulkModelMutation):
    class Meta:
        model = User


# Add to graphene schema as usual
class Mutation(graphene.ObjectType):
    user_create = UserCreateMutation.Field()
    ....

schema = graphene.Schema(mutation=Mutation)

GraphQl usage

The generated GraphQl schema can be modified with Meta fields as described above in UserCreateMutation.

By default all mutations have errors field with field and messages that contain validation errors from rest-framework serializer or lookup errors. For now permission denied and other exceptions will not use this error reporting, but a default one, for usage see tests.

# default argument name is input
# default return field name is model name
mutation userCreate (input: {username: "myUsername"}) {
    user {
        id
        username
    }
    errors {
        field
        messages
    }
}


# Bulk operations return 'count' and errors
mutation userBulkCreate (input: [{username: "myUsername"}, {username:"myusername2"}]) {
    count
    errors {
        field
        messages
    }
}

# update mutations
# update and delete mutations by default specify lookup field 'id' or 'ids' for bulk mutations
mutation {
    userUpdate (id: 2, input: {username:"newUsername"} ) {
        user {
            id
            username
        }  
        errors {
            field
            messages
        }
    } 
}   


mutation {
    userBulkUpdate (ids: [2, 3], isActive: false ) {
        count
        errors {
           field
           messages
        }
    }
}  


# delete mutations
mutation {
    userDelete (id: 1) {
        user {
            id
        }
        errors {
           field
           messages
        }
    }
}  


mutation {
    userBulkDelete (ids: [1, 2, 3]) {
        count
        errors {
           field
           messages
        }
    }
}  

Adding funcionality

All classes are derived from graphene.Mutation. When you want to override some major functionality, the best place probabably is perform_mutate, which is called after permission checks from graphene mutate.

In general probably the main functions that you want to override are: save() and get_object() for single object mutations or get_queryset() for bulk mutations.
get_object or get_queryset you should override to add more filters for fetching the object.
save performs final save/update/delete to database and you can add additional fields there.

Examples:

# lets only update users that are inactive and add some random field
class UserUpdateInactiveMutation(mutations.UpdateModelMutation):
    class Meta:
        model = User

    @classmethod
    def get_object(cls, object_id, info, **input):
    # can get the object first and then check
        obj = super(UserUpdateInactiveMutation, cls).get_object(object_id, info, **input)
        if obj.is_active:
            return None
        return obj

    @classmethod
    def save(cls, serializer, root, info, **input):
        saved_object = serializer.save(updated_by=info.context.user)
        return cls.return_success(saved_object)


# same but for bulk mutation we have to override get_queryset
class UserBulkUpdateInactiveMutation(mutations.UpdateBulkModelMutation):
    class Meta:
        model = User

    @classmethod
    def get_queryset(cls, object_ids, info, **input):
        qs = super(UserBulkUpdateInactiveMutation, cls).get_queryset(object_ids, info, **input)
        qs.filter(is_active=False)
        return qs

For the whole function flow, please check the Base models in django_model_mutations\mutations.py. It was inspired by rest framework, so you can find functions like get_serializer_kwargs, get_serializer, validate_instance (for example here you can override default ValidationError exception and return None if you don't want exception of non existing id lookup etc.)

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].