如何分页结果并通过Graphql中的ForeignKey字段对其进行过滤?

时间:2019-04-10 03:18:10

标签: python django api graphql graphene-python

我正在用Django写一个graphql api。我想像下面的例子一样进行搜索。我是使用graphql的新手,我只知道如何返回所有对象。所以,我想知道1)如何将结果分成不同的页面,每个页面包含10个结果。 2)如何通过ForeignKey字段过滤结果?就像,我想用Expense.objects过滤ExpenseDetail.date并输出它。我尝试使用expense_set进行搜索,但graphql报告错误。我该如何解决以上两个问题。非常感谢。

Models.py(简化很多):

class Expense(BaseModel):
    id = models.AutoField()
    price = models.FloatField()
class ExpenseDetail(BaseModel):
    id = models.CharField()
    date = models.DateField()
    expense = models.ForeignKey(Expense, on_delete=models.CASCADE, default=None, null=True, blank=True)

Schema.py:

class ExpenseType(DjangoObjectType):
    class Meta:
        model = Expense

class Query(graphene.ObjectType):
    list_expense = graphene.List(ExpenseType, search=graphene.String())

    def resolve_list_expense(self, info, search=None,  **Kwargs):
        return Expense.objects.all()

Graphql:

query{
  listExpense(ExpenseId:"", page:1, pageSize:10, startdate:"", enddate:"") {
    page
    pageSize
    totalSize
    expense_set{
               date
               }
  }
}

0 个答案:

没有答案