djangographqlgraphene-python

Django - edit default graphene Set query


i am building a django application with graphql and i have two models

Column Model:

class Column(models.Model):
    name = models.CharField(max_length=100)

Task Model:

class Task(models.Model):
    column = models.ForeignKey(Column, on_delete=models.CASCADE)
    content = models.CharField(max_length=255)
    position = models.IntegerField()

and i have a query to query all Columns and their tasks

class ColumnType(DjangoObjectType):
    class Meta:
        model = Column

class Query(object):
    columns = graphene.List(ColumnType)

    def resolve_columns(self, info, **kwargs):
        return Column.objects.all()

and i can query this by:

{
    columns {
        id
        taskSet{
            content
        }
    }
}

but by doing this i cant add fields to taskSet function so i want to add a filter that will get only the first 20 tasks


Solution

  • If you always want to show only the first 20 results you can try this:

    class Query(object):
        columns = graphene.List(ColumnType)
    
        def resolve_columns(self, info, **kwargs):
            return Column.objects.all()[0:20]
    

    Or if you want to give give a filter number when you run the query you can try something like this:

    class Query(object):
        columns = graphene.List(ColumnType, myFilter=Int())
    
        def resolve_columns(self, info, **kwargs):
            my_filter = kwargs.get('myFilter')
            if my_filter is not None:
                return Column.objects.all()[0:my_filter]
            return None
    

    And call it like:

    {
        columns {
            id
            taskSet(myFilter:20){
                content
            }
        }
    }