[Django]-How to add a custom field that is not present in database in graphene django

7👍

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)

1👍

Small example:

Brand model

class Brand(models.Model):
    name = models.CharField(max_length=100, null=False)

    def __str__(self):
        return self.name

BrandNode

class BrandNode(DjangoObjectType):
    # extra field INT
    extra_field_real_id_plus_one = graphene.Int()

    def resolve_extra_field_real_id_plus_one(parent, info, **kwargs):
        value = parent.id + 1
        print(f'Real Id: {parent.id}')
        print(f'Id ++: {value}')
        return value

    class Meta:
        model = Brand
        filter_fields = {
            'name': ['icontains', 'exact']
        }
        interfaces = (relay.Node,)

extra_field_real_id_plus_one is the extra field. You can get any value from the original model, exactly from the parent parameter. You can calculate or format whatever you want and just you need to return the value.
You can get the extra field calculated value in queries, mutations, etc.

Leave a comment