Graphene-django: Examples on adding calculated fields

Created on 20 Dec 2016  路  6Comments  路  Source: graphql-python/graphene-django

Exposing fields that are in the db/model works fine, but what about calculated fields? For example, if I want to expose a field called Author.book_count that will obviously not be queriable or editable, how can I do that?

help wanted wontfix 馃摉 documentation

Most helpful comment

@skorokithakis checkout issue this issue:
https://github.com/graphql-python/graphene/issues/101

Import graphene and do:
vote_count = graphene.Int(source='vote_count')

'vote_count' is my property.

Full code:

class QuestionNode(DjangoObjectType):
    vote_count = graphene.Int(source='vote_count')
    class Meta:
        model = Question
        # filter_fields = ['name', 'ingredients']
        interfaces = (relay.Node, )

All 6 comments

@skorokithakis checkout issue this issue:
https://github.com/graphql-python/graphene/issues/101

Import graphene and do:
vote_count = graphene.Int(source='vote_count')

'vote_count' is my property.

Full code:

class QuestionNode(DjangoObjectType):
    vote_count = graphene.Int(source='vote_count')
    class Meta:
        model = Question
        # filter_fields = ['name', 'ingredients']
        interfaces = (relay.Node, )

Ah, thanks! It would be great if this was in the docs.

How to add a new field that its type is a list?

How do I resolve a django object along with an extra, calculated field like below during a query?

class ProjectType(DjangoObjectType):
    class Meta:
        model = Project

    extra_field = graphene.String()


class Query(ObjectType):
    project = graphene.Field(ProjectType,
                             name=graphene.String())

    def resolve_project(self, info, name):

        if id is not None:
            return Project.objects.get(pk=id) # how do I populate `extra_field` here?


        return None

@paymog

    def resolve_project(self, info, name):

        if id is not None:
            project = Project.objects.get(pk=id) # how do I populate `extra_field` here?
            return ProjectType(**project, extra_field="something")


        return None

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dan-klasson picture dan-klasson  路  4Comments

licx picture licx  路  3Comments

ZuluPro picture ZuluPro  路  3Comments

x9sheikh picture x9sheikh  路  4Comments

Eraldo picture Eraldo  路  3Comments