0soft/graphene-django-plus

When and where to set some field value before mutation?

Rainshaw opened this issue · 6 comments

Hello, I have a model that has a "owner" field with it.

I have two questions:

  1. how can i make this field not required or even hidden on graphql api?
  2. how can i set it to the request user before save? or raise error when the both do not match if Q1 can not be solved.

Looking forward to your reply.

Hey @RainshawGao

  1. It depends. If you are talking regarding the type itself, take a look at the graphene-django documentation. If it is at the mutation, you can use exclude_fields to exclude some fields or only_fields to define a list of the fields that will be exposed (obs. graphene-django works very alike for the query, except that they use exclude and fields if I'm not mistaken)

  2. There's a lot of ways. You can use the before_save hook at the mutation to do that. You can override the clean_input method (https://github.com/0soft/graphene-django-plus/blob/master/graphene_django_plus/mutations.py#L607) and add the user yourself (call super() and then add the user by hand), etc

nice to hear from you!! Thanks for your reply 😊

as in my scenery, the owner field has to be exposed so admins could create the instance for other user, and this field is not null so it is marked required, I have tried a lot of ways to mark it not required but they all not work 😔

so I finally use the second way, to verify the request user and the owner field value in clean_input method and raise error.

Thank you again~

To automatically mark it as not required you need to mark it with blank=True and have a default value on it (both on the django field)

You can also define a list of required_fields at the mutation, then the mutation will only consider those as required and force everything else to not required.

yes, I had tried to define the required_fields but I get validationerror in clean_instance() func.
If I mark the field as blank=True or with default value, it works.
I have to keep the field as it is for it also affects the django admin page, and the model must have the owner field. if I change the field, there is too many code needing to change. (On the other hand, I also do not have permission to modify the model in my compony....T^T)

Hey @RainshawGao

Is the issue solved? Asking so I can close it here.

yes! I just make it using clean_input, clean_instance and before_save func