devind-team / devind-django-helpers

Django helpers.
MIT License
0 stars 1 forks source link

RetrieveField for detail entity #4

Open Luferov opened 2 years ago

Luferov commented 2 years ago

Very often it happens that you need to get one entity from the database by some key. For example:

import graphene

class Query(graphene.ObjectType):
    object = graphene.Field(ObjectType, object_id=graphene.Int(required=True), description)

    @staticmethod
    def resolve_object(root: Any, info: ResolveInfo, object_id: int):
         return get_object_or_404(Object, pk=object_id)

Replaced by:

from typing import Optional
import graphene

class Query(graphene.ObjectType):
    object = RetrieveField(ObjectType, key: Optional[str]='object_id', description: Optional[str] = 'Description')

object may be user, group, etc. key and description may generate automatically or set by user. Clarification about key: UserType -> key = user_id, GroupType -> key = group_id, etc.

SquakR commented 2 years ago

I think, the object_id argument must be graphene.ID instead of graphene.Int. The id can be either a regular id (graphene.Int) or a global id (graphene.ID), but we assumed earlier that type must be graphene.ID in both cases. The difference may be discovered in the resolver. If the ObjectType implements relay.Node interface then the id is global else it is regular.