graphql-python / graphql-python/graphene-django

Allow to use DjangoModelFormMutation only for update

Open
#1,252 0 comments 0 reactions 0 assignees View on GitHub
✨enhancement
Dominant language
Python
Stars
4.4k
Forks
760
PR merge metrics
No merged PRs in 30d

Description

`DjangoModelFormMutation` allows as perform two operations create or update if not specified `exclude_fields = ('id', )`
For example

```python
class MyMutation(DjangoModelFormMutation):
class Meta:
form_class = MyForm
```

For this mutation, graphene generates id field [as not required ](https://github.com/graphql-python/graphene-django/blob/main/graphene_django/forms/mutation.py#L145) and [fetches instance for form if id passed](https://github.com/graphql-python/graphene-django/blob/main/graphene_django/forms/mutation.py#L63-L65) (Update operation). If Id not passes and the instance is none Django creates a new object in DB (create operation)

This doesn't allow to use of `DjangoModelFormMutation` only for update operations, because ID is not required.

**Describe the solution you'd like**
For specifying available operations we can add a new option as well as for [DRF serializers ](https://github.com/graphql-python/graphene-django/blob/main/graphene_django/rest_framework/mutation.py#L68)

```python
class MyMutation(DjangoModelFormMutation):
class Meta:
form_class = MyForm
model_operations=("create", "update"), // <<-- New option
```

**Describe alternatives you've considered**

Now is a possible solution as a workaround: passed 'id' to excluded fields, add id to `Input` and fetch instance for form manually

```python
class MyMutation(DjangoModelFormMutation):
class Meta:
form_class = MyForm
exclude_fields = ('id',)

class Input:
# workaround to pass id as required argument for DjangoModelFormMutation
id = graphene.ID(required=True)

@classmethod
def get_form_kwargs(cls, root, info, **input) -> dict:
kwargs = super().get_form_kwargs(root, info, **input)
kwargs["instance"] = ... // get instance
return kwargs
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.