标签: graphene-python

在不使用 Relay 的情况下对石墨烯查询使用 django_filters

在 Django 中将石墨烯与 Relay 一起使用时,可以选择在查询数据时使用过滤。

class AnimalNode(DjangoObjectType):
    class Meta:
        model = Animal
        filter_fields = ['name', 'genus', 'is_domesticated']
        OR
        filter_fields = {
            'name': ['exact', 'icontains', 'istartswith'],
            'genus': ['exact'],
            'is_domesticated': ['exact'],
        }
        interfaces = (relay.Node, )
Run Code Online (Sandbox Code Playgroud)

是否可以在我不使用中继时以这种方式使用过滤,或者它是仅中继功能?我在石墨烯文档中没有看到对非中继的任何过滤,因此无法确定如何进行此操作。

django graphene-python

9
推荐指数
1
解决办法
940
查看次数

如何在石墨烯中使用 DRF 序列化器

我正在按照本教程GrapheneDjango一起使用,一切都进行得很顺利,直到我到达了与 Django Rest Framework集成部分

本节说您可以通过创建序列化器克隆来将DRF序列化器与Graphene重用,但它没有说明如何处理此类克隆以将DRF序列化器与Graphene重用。

这些是我的序列化程序和克隆:

from rest_framework import serializers
from graphene_django.rest_framework.mutation import SerializerMutation
from GeneralApp.models import Airport
from ReservationsManagerApp.serializers import ReservationSerializer
from ReservationsManagerApp.models import ReservationComponent, ReservationHotel, ReservationRoundtrip, ReservationTransfer, ReservationTour, ReservationService, Hotel

class ReservationMutation(SerializerMutation):
    class Meta:
        serializer_class = ReservationSerializer

class ReservationComponentGraphSerializer(serializers.ModelSerializer):
    component = serializers.SerializerMethodField()

    class Meta:
        model = ReservationComponent
        fields = ('id', 'reservation', 'dertour_bk', 'day', 'content_type', 'object_id', 'comment', 'is_invoiced', 'component')

    def get_component(self, …
Run Code Online (Sandbox Code Playgroud)

python django django-rest-framework graphene-python

9
推荐指数
1
解决办法
3098
查看次数

如何使石墨烯输入类变量可选?

在 GraphQL 更新突变中,我希望能够传入子对象的值,但我希望这些值中的每一个都是可选的。

所以我创建了一个这样的输入类:

class CityCouncilInput(graphene.InputObjectType):
  mayor = graphene.String()
  treasurer = graphene.String()
Run Code Online (Sandbox Code Playgroud)

现在,我希望能够同时为市长和财务主管传递值,或者仅传递其中一个值。

Pleas 知道如果传入所有值,我的代码就可以正常工作。我只希望这些字段值是可选的。我怎么做?

罗伯特

graphene-python

8
推荐指数
1
解决办法
5400
查看次数

石墨烯graphql字典作为一种类型

我是石墨烯的新手,我正在尝试将以下结构映射为对象类型,但完全没有成功

    {
  "details": {
    "12345": {
      "txt1": "9",
      "txt2": "0"
    },
    "76788": {
      "txt1": "6",
      "txt2": "7"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

任何指导都非常
感谢

python graphql graphene-python

8
推荐指数
2
解决办法
2900
查看次数

如何根据Graphene/Django上的用户类型限制模型上的字段访问?

假设我有一个模型:

class Employee(models.Model):
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=60)
    salary = models.DecimalField(decimal_places=2)
Run Code Online (Sandbox Code Playgroud)

我希望任何人都能够访问first_name和last_name但只希望某些用户能够读取工资,因为这是机密数据.

然后我想限制工资的写/更新给一个甚至不同类型的用户.

如何根据请求用户限制字​​段读/写/更新?

编辑:

这是在GraphQL API上下文中.我正在使用石墨烯.我想在解析器功能中看到可扩展的解决方案.

python django graphene-python

8
推荐指数
1
解决办法
1678
查看次数

具有多对多和直通表的 Graphene-django

我的应用程序与直通模型有几个多对多关系如下所示:

class Person(models.Model):
    name = models.CharField()

class Group(models.Model):
    name = models.CharField()
    members = models.ManyToManyField(Person, through='Membership')

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()  # Extra info on the relationship
Run Code Online (Sandbox Code Playgroud)

在 graphql 中表示这些数据而没有成员资格的中间类型(选项 A)似乎很直观:

{
  "data": {
    "persons": [
      {
        "id": "1",
        "name": "Jack",
        "groups": [
          {
            "id": 3,                     # From Group-model
            "name": "Students",          # From Group-model
            "date_joined": "2019-01-01"  # From Membership-model
          },
          ...
        ]
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

对比选项 B:

{
  "data": { …
Run Code Online (Sandbox Code Playgroud)

django graphql graphene-python

8
推荐指数
1
解决办法
1128
查看次数

如何使用 Graphene GraphQL 解析嵌套在另一种类型中的字段?

我有 3 个文件:authors.py,posts.pyschema.py.

帖子有一个作者,查询构建在架构文件中。

我试图Author从内部Post解析而不在 中声明解析器函数Post,因为Author已经声明了一个解析器函数。以下代码有效,但我必须resolve_authorPost类型内部进行引用,这似乎不对。我认为 Graphene 应该parent直接将参数传递给Author,不是吗?

如果我没有authorPost类型中设置解析器,它只会返回null.

模式.py

import graphene
from graphql_api import posts, authors


class Query(posts.Query, authors.Query):
    pass


schema = graphene.Schema(query=Query)
Run Code Online (Sandbox Code Playgroud)

作者.py

from graphene import ObjectType, String, Field


class Author(ObjectType):
    id = ID()
    name = String()


class Query(ObjectType):
    author = Field(Author)

    def resolve_author(parent, info):
        return {
            'id': '123',
            'name': …
Run Code Online (Sandbox Code Playgroud)

python graphql graphene-python

8
推荐指数
1
解决办法
4187
查看次数

如何有条件地记录 graphene-django 中的异常?

每当引发异常时,它们都会记录在控制台中(如果使用了 Sentry,则记录在 Sentry 中)。

许多这些例外仅旨在向用户显示。例如,django-graphql-jwt引发PermissionDenied异常login_required装饰

问题是这会在测试/开发期间污染控制台输出,并在生产期间将有效错误记录到 Sentry。对于上述示例等例外情况,它仅打算向用户显示,而不是记录。

作为一种解决方法,我尝试编写中间件来捕获抛出的任何异常:

class ExceptionFilterMiddleware:
    IGNORED_EXCEPTIONS = (
        # Local exceptions
        ValidationException,
        # Third-party exceptions
        JSONWebTokenExpired,
        PermissionDenied,
    )

    def on_error(self, error):
        if not isinstance(error, self.IGNORED_EXCEPTIONS):
            return error

    def resolve(self, next, *args, **kwargs):
        return next(*args, **kwargs).catch(self.on_error)
Run Code Online (Sandbox Code Playgroud)

但是如果异常被捕获或未返回,它不再填充errors查询/变异输出中的字段。因此,所有错误都被记录下来,没有办法有条件地记录异常。

这意味着唯一的解决方案是创建一个日志过滤器,如下所示:

def skip_valid_exceptions(record):
    """
    Skip exceptions for errors only intended to be displayed to the API user.
    """
    skip: bool = False

    if record.exc_info:
        exc_type, exc_value = …
Run Code Online (Sandbox Code Playgroud)

django graphene-python graphene-django

8
推荐指数
1
解决办法
1337
查看次数

Graphene-Django 和多对多关系查找

我有两个 Django 模型——老师和学生,并且有多对多的关系。老师可以有多个学生,学生也可以有多个老师。有一种称为“备注”的“通过”模型,教师可以在其中将学生标记为最喜欢的。

我是 GraphQL 的新手。我正在尝试实现两个查询:
1. 老师和他们所有的学生
2. 老师和他们最喜欢的学生

我在实施第二个查询时遇到了困难,并且一直无法这样做。

模型.py

SUBJECTS = (
    ("Maths", "Maths"),
    ("Chemistry", "Chemistry"),
    ("Physics", "Physics")
)

class Student(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField(default=0)

    def __str__(self):
        return self.name

class Teacher(models.Model):
    name = models.CharField(max_length=100)
    subject = models.CharField(max_length=100, choices=SUBJECTS)
    students = models.ManyToManyField(Student, through="Remarks")

    def __str__(self):
        return self.name

class Remarks(models.Model):
    student = models.ForeignKey(Student, related_name="student", on_delete=models.DO_NOTHING)
    teacher = models.ForeignKey(Teacher, related_name="teacher", on_delete=models.DO_NOTHING)
    favorite = models.BooleanField(default=False, choices=(
        (True, "Yes"),
        (False, "No")
    ))

Run Code Online (Sandbox Code Playgroud)

模式.py

import graphene
from graphene import relay, ObjectType …
Run Code Online (Sandbox Code Playgroud)

django graphql graphene-python graphene-django django-graphql-jwt

8
推荐指数
1
解决办法
1209
查看次数

类型为 \"CreateUaction\" 的字段 \"createUaction\" 必须有一个子选择。"

这是我第一次使用石墨烯,对它没有很好的掌握。所以基本上是制作一个博客,用户可以在博客上点赞、评论和添加帖子到他最喜欢的,并互相关注。

我为所有用户操作制作了一个单独的模型

  class user_actions(models.Model):
      user = models.ForeignKey(User, on_delete=models.CASCADE)
      liked_post = models.ForeignKey(Post, related_name='post_likes', 
      on_delete=models.CASCADE)
      liked_comments = models.ForeignKey(Comment, 
      related_name='comment_likes', on_delete=models.CASCADE)
      fav = models.ForeignKey(Post, related_name='fav_post', 
      on_delete=models.CASCADE)
      target = models.ForeignKey(User, related_name='followers', 
      on_delete=models.CASCADE, null=True, blank = True)
      follower = models.ForeignKey(User, related_name='targets', 
      on_delete=models.CASCADE, null = True, blank = True)

      def __str__(self):
          return self.user.username
Run Code Online (Sandbox Code Playgroud)

因此,我对所有操作进行了更改,我正在尝试遵循 DRY 原则并将它们汇总在一起,我可能在这里做错了什么,新编码人员尽我所能:D

 class UactionInput(InputObjectType):
    liked_post_id = graphene.Int()
    fav_post_id = graphene.Int()
    comment_id = graphene.Int()
    target_id = graphene.Int()
    follower_id = graphene.Int()

 class CreateUaction(graphene.Mutation):
    user = graphene.Field(UactionType)

    class Arguments:
       input =  UactionInput()


    def mutate(self, info, …
Run Code Online (Sandbox Code Playgroud)

django graphql graphene-python graphene-django

7
推荐指数
1
解决办法
8211
查看次数