简体   繁体   中英

Graphene-Django - how to pass an argument from Query to class DjangoObjectType

First of all, thanks. it has been 1 year without asking question as I always found an answer. You're a tremendous help.

Today, I do have a question I cannot sort out myself. Please, I hope you would be kind enough to help me on the matter.

Context: I work on a project with Django framework, and I have some dynamic pages made with react.js. The API I'm using in between is graphQL based. Apollo for the client, graphene-django for the back end.

I want to do a dynamic pages made from a GraphQL query having a set (a declared field in the class DjangoObjectType made from a Django query), and I want to be able to filter dynamically the parent with a argument A, and the set with argument B. My problem is how to find a way to pass the argument B to the set to filter it.

The graphQL I would achieved based on graphQL documentation

query DistributionHisto
(
  $id:ID,
  $limit:Int
)
{
  distributionHisto(id:$id)
  {
    id,
    historical(limit:$limit)
    {
       id,
       date,
       histo
    }
  }
}

But I don't understand how to pass (limit:$limit) to my set in the back end.

Here my schema.py

import graphene
from graphene_django.types import DjangoObjectType

class DistributionType(DjangoObjectType):
    class Meta:
        model = DistributionTuple

    historical = graphene.List(HistoricalTimeSeriesType)

    def resolve_historical(self, info):
        return HistoricalTimeSeries.objects.filter(
            distribution_tuple_id=self.id
            ).order_by('date')[:2]

class Query(object):
    distribution_histo = graphene.List(
        graphene.NonNull(DistributionType),
        id=graphene.ID(),
        limit=graphene.Int()
        )

    def resolve_distribution_histo(
            self, info, id=None, limit=None):
        filter_q1 = {'id': id} if id else {}
        return DistributionTuple.objects.filter(**filter_q1)

I have tried few things, but I didn't find a way to make it to work so far.

At the moment, as you see, the arg "limit" reaches a dead end in def resolve*, where ideally, it would be pass up to the class DistributionSetHistoType where it would replace the slice [:2] by [:limit] in resolve_distribution_slice_set()

I hope I have been clear, please let me know if it's not the case.

Thanks for your support.

This topic called pagination .

  1. front end seletion
const { loading, error, data, fetchMore } = useQuery(GET_ITEMS, {
  variables: {
    offset: 0,
    limit: 10
  },
});
  1. backend selction
  • the number 10 in .count(10) represent the first 10 elements in the array
DistributionTuple.objects.filter(**filter_q1).count(10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM