簡體   English   中英

Graphene-Django - 如何將參數從查詢傳遞到 class DjangoObjectType

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

首先,謝謝。 已經有 1 年沒有提問了,因為我總能找到答案。 你是一個巨大的幫助。

今天,我確實有一個我自己無法解決的問題。 拜托,我希望你能在這件事上幫助我。

背景:我在一個使用 Django 框架的項目上工作,我有一些用 react.js 制作的動態頁面。 我在兩者之間使用的 API 是基於 graphQL 的。 Apollo 用於客戶端,graphene-django 用於后端。

我想做一個由 GraphQL 查詢制成的動態頁面,該查詢具有一組(class DjangoObjectType 中的聲明字段,由 Django 制成),並且我希望能夠使用父查詢動態設置過濾器參數 B。我的問題是如何找到一種方法將參數 B 傳遞給集合以對其進行過濾。

我將根據 graphQL 文檔實現的 graphQL

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

但我不明白如何在后端將 (limit:$limit) 傳遞給我的集合。

這是我的 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)

我嘗試了幾件事,但到目前為止我還沒有找到讓它工作的方法。

目前,如您所見,arg“limit”在 def resolve* 中達到了死胡同,理想情況下,它將被傳遞到 class DistributionSetHistoType 在那里它將切片 [:2] 替換為 [:limit] resolve_distribution_slice_set()

我希望我已經清楚了,如果不是這樣,請告訴我。

謝謝你的支持。

這個話題叫做pagination

  1. 前端選擇
const { loading, error, data, fetchMore } = useQuery(GET_ITEMS, {
  variables: {
    offset: 0,
    limit: 10
  },
});
  1. 后端選擇
  • .count(10)中的數字10表示數組中的前 10 個元素
DistributionTuple.objects.filter(**filter_q1).count(10)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM