question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Need custom fields in the graphql response on the basis of db values

See original GitHub issue

Hi , I have table which has totalCpuCount, diffCount, wisbCount, totalRequests etc etc (CapacityModel) per day basis for each application , I need to calculate the avg of the day and return the response in the custom fields. I cant store these custom field in the db

Basically in the response I get the list of node for each application (per date) but I want the average for the day.

schema.py

class CapacityNode(DjangoObjectType):
    deltas = generic.GenericScalar()
    class Meta:
        model = CapacityModel
        filter_fields = ['date', 'type', 'name', 'app']
        interfaces = (relay.Node,)


class Query(ObjectType):    
    capacity = relay.Node.Field(CapacityNode)
    all_capacity = DjangoFilterConnectionField(CapacityNode)

I need response something like

{
  "data": {
    "allCapacity": {
      "edges": [
        {
          "node": {
            "date": "2019-10-12",
            "avgTotalCpuCount": 11716,
            "avgDiffCount": -1375,
            "avgWisbCount": 2808,
            "avgTotalRequests": 247927
            "avgSkynetDefineInDnsCount": 1430,
            "avgCmsNonGenesisCount": 1547,
            "avgPoolCount": 10,}
		  }
		}
      ]
	}
  }
}

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
monikadixitcommented, Feb 12, 2020

I was able to resolve this ,

`class avgCapacityNode(ObjectType): avgCpu=graphene.Float() avgWisb = graphene.Float()

class Query(ObjectType):

extra_field = graphene.Field(avgCapacityNode, date=graphene.String(), manager=graphene.String())

def resolve_extra_field(self, info, **kwargs):
    date = kwargs.get('date', None)
    manager =kwargs.get('manager', None)
    # manager =kwargs.get('manager', None)
    print(date)
    if date:
        avgCpu = CapacityModel.objects.filter(date = date).filter(manager = manager).aggregate(Avg('wisb') )
        avgWisb = CapacityModel.objects.filter(date = date).aggregate(Avg('total_requests') )
        avgCapacityNode.avgCpu = avgCpu['wisb__avg']
        avgCapacityNode.avgWisb = avgWisb['total_requests__avg']
        return avgCapacityNode
    else:
        avgCpu = CapacityModel.objects.filter(date = '2019-10-02').aggregate(Avg('wisb') )
        avgWisb = CapacityModel.objects.filter(date = '2019-10-02').aggregate(Avg('total_requests') )
        avgCapacityNode.avgCpu = avgCpu['wisb__avg']
        avgCapacityNode.avgWisb = avgWisb['total_requests__avg']
        return avgCapacityNode`
0reactions
team-jaitqcommented, Jan 14, 2022

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

GraphQL schema basics
This schema defines a hierarchy of types with fields that are populated from your back-end data stores. The schema also specifies exactly which...
Read more >
GraphQL Tutorial: how to use fields, fragments, and more
You can make many objects of the same type, each with its own values for the defined fields.
Read more >
Queries and Mutations - GraphQL
On this page, you'll learn in detail about how to query a GraphQL server. Fields#. At its simplest, GraphQL is about asking for...
Read more >
Creating a Calculated Field in GraphQL Using a Custom ...
Learn how to use Dgraph Lambda to have dynamic data in your database and implement business logic in your GraphQL schema.”
Read more >
GraphQL Queries to fetch data - Hasura
We ask the server for all the todos and their titles in the above query. The “ todos " represents an object and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found