Search code examples
djangographene-django

How to filter with graphene.filter


I want to filter Notifications by user.username, how can I do it?

models.py

class Notification(BaseModelo):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.CharField(max_length=200)
    state = models.BooleanField(default=False)

schema.py

class NotificationNode(DjangoObjectType):

    class Meta:
        model = Notification
        filter_fields = ['user']
        interfaces = (Node, )

class Query(ObjectType):
    user = Node.Field(UserNode))
    all_users = DjangoConnectionField(UserNode)

    notification = Node.Field(NotificationNode)
    all_notifications = DjangoFilterConnectionField(NotificationNode)

Solution

  • You can use the library django-filter and the standard Django double-underscore syntax for using attributes of a related model. Namely, you should write 'user__username' in your filter field.

    class NotificationNode(DjangoObjectType):
    
        class Meta:
            model = Notification
            filter_fields = { 'user__username': ['exact'], }
            interfaces = (Node, )
    

    You can see an example of this being used here: https://docs.graphene-python.org/projects/django/en/latest/tutorial-relay/#schema