簡體   English   中英

在沒有中繼的情況下使用帶有graphene-django的子字段中的參數進行分頁

[英]Use parameters in subfields with graphene-django without relay for pagination purpose

我正在使用帶有 django 的石墨烯,我正在努力做一些在我腦海中應該非常簡單的事情,但我沒有發現它在石墨烯文檔或 github 的任何地方都有記錄,我也沒有在這里看到類似的問題。 我發現最接近它的是: https://www.howtographql.com/graphql-python/8-pagination/但正如你所看到的,我必須在父解析器中聲明我不想的參數.

我有這樣的查詢

  getUser(id: $userIdTarget) {
    id
    username
    trainings{
      id
      name
      sessions{
        id
        name
      }
    }
  }
}

我想在會話子字段中實現分頁。 所以這就是我想要的:

  getUser(id: $userIdTarget) {
    id
    username
    trainings{
      id
      name
      sessions(first:10){
        id
        name
      }
    }
  }
}

在解析器中我會實現這樣的東西:

def resolve_sessions(root, info, first=None, skip=None):
        if skip:
            return gql_optimizer.query(Session.objects.all().order_by('-id')[skip:], info)
        elif first:
            return gql_optimizer.query(Session.objects.all().order_by('-id')[:first], info)
        else:
            return gql_optimizer.query(Session.objects.all().order_by('-id'), info)

(gql_optimizer 只是我使用的一個優化包裝庫)

但是,這不起作用,因為字段會話對應於 model Session 的列表,這是根據我的 django 模型進行訓練的 fk,所以這是由 DjangoObjectType 自動解決的,所以我確定這些類型不是真正的 DjangoObjectType如何定制這些解析器(或者如果可能的話)。

我將在下面留下相關的模型和類型:

Session model

class Session(models.Model):
    name = models.CharField(max_length=200, help_text='Session\'s name')
    category = models.CharField(max_length=240, choices=SESSION_CATEGORIES, default="practice",
                                help_text='Session type. Can be of \'assessment\''
                                          'or \'practice\'')
    total_steps = models.IntegerField(default=1, help_text='Amount of steps for this session')
    created_at = models.DateTimeField(editable=False, default=timezone.now, help_text='Time the session was created'
                                                                                      '(Optional - default=now)')
    completed_at = models.DateTimeField(editable=False, null=True, blank=True, help_text='Time the session was finished'
                                                                                         '(Optional - default=null)')
    is_complete = models.BooleanField(default=0)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="training_sessions", on_delete=models.DO_NOTHING)
    training = models.ForeignKey("Training", related_name="sessions", on_delete=models.CASCADE)

    def __str__(self):
        return self.name

用戶類型

class UserType(DjangoObjectType):
    class Meta:
        model = get_user_model()
        fields = "__all__"


    @classmethod
    def get_queryset(cls, queryset, info, **kwargs):
        if info.variable_values.get('orgId') and info.variable_values.get('orgId') is not None:
            return queryset.order_by('username')
        return queryset

會話類型

class SessionType(DjangoObjectType):
    class Meta:
        model = Session
        fields = "__all__"
        convert_choices_to_enum = False

    @classmethod
    def get_queryset(cls, queryset, info, **kwargs):
        if info.variable_values.get('userId') and info.variable_values.get('userId') is not None:
            return queryset.filter(Q(user_id=info.variable_values.get('userId'))).order_by('-id')
        return queryset

培訓類型

class TrainingType(gql_optimizer.OptimizedDjangoObjectType):
    class Meta:
        model = Training
        fields = "__all__"
        convert_choices_to_enum = False

可以擴展您的類型以添加更多不在 Django model 中的字段 - 也許這就是您正在尋找向查詢中注入更多數據的技術?

class TrainingType(gql_optimizer.OptimizedDjangoObjectType):
    my_extra_field = graphene.Int() # for example

    class Meta:
        model = Training
        fields = "__all__"
        convert_choices_to_enum = False

您還可以覆蓋使用DjangoObjectType創建的默認解析器。

暫無
暫無

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

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