如何使用 graphene.filter 进行筛选

How to filter with graphene.filter

我想按 user.username 过滤通知,我该怎么做?

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)

您可以使用库 django-filter 和标准 Django 双下划线语法来使用相关模型的属性。即,您应该在筛选字段中写入 'user__username'。

class NotificationNode(DjangoObjectType):

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

您可以在此处查看使用的示例:https://docs.graphene-python.org/projects/django/en/latest/tutorial-relay/#schema