Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add a custom field that is not present in database in graphene django

so my model looks like

class Abcd(models.Model):
    name = models.CharField(max_length=30, default=False)
    data = models.CharField(max_length=500, blank=True, default=False)

need to pass a dictionary at query time which is not a part of model, query is

query {
  allAbcd(Name: "XYZ") {
    edges {
      node {
        Data
      }
    }
  }
}

How does one pass such a custom field with the query ?.

This custom field is required for other process purpose.

like image 750
nish Avatar asked Dec 03 '25 03:12

nish


1 Answers

Graphene uses Types to resolve nodes, which are not at all tied to the model, you can even define a Graphene Type which is not associated with any model. Anyway the usecase you're looking for is pretty simple. Let's say that we have a model name User per say, I'm assuming that this Data needs to be resolved by the Model's resolver.

from graphene.relay import Node
from graphene import ObjectType, JSONField, String
from graphene_django import DjangoObjectType

from app.models import User

class UserType(DjangoObjectType):
    class Meta:
        filter_fields = {'id': ['exact']}
        model = User

    custom_field = JSONField()
    hello_world = String()

    @staticmethod
    def resolve_custom_field(root, info, **kwargs):
        return {'msg': 'That was easy!'} # or json.dumps perhaps? you get the idea

    @staticmethod
    def resolve_hello_world(root, info, **kwargs):
        return 'Hello, World!'


class Query(ObjectType):
    user = Node.Field(UserType)
    all_users = DjangoFilterConnectionField(ProjectType)
like image 106
frozenOne Avatar answered Dec 05 '25 17:12

frozenOne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!