【问题标题】:how to add a custom field that is not present in database in graphene django如何在石墨烯django中添加数据库中不存在的自定义字段
【发布时间】:2020-07-05 15:14:36
【问题描述】:

所以我的模型看起来像

class Abcd(models.Model):
    name = models.CharField(max_length=30, default=False)
    data = models.CharField(max_length=500, blank=True, default=False)

需要在查询时传递一个字典,它不是模型的一部分,查询是

query {
  allAbcd(Name: "XYZ") {
    edges {
      node {
        Data
      }
    }
  }
}

如何通过查询传递这样一个自定义字段?

此自定义字段是其他处理目的所必需的。

【问题讨论】:

    标签: django graphene-python graphene-django


    【解决方案1】:

    小例子:

    品牌型号

    class Brand(models.Model):
        name = models.CharField(max_length=100, null=False)
    
        def __str__(self):
            return self.name
    

    品牌节点

    class BrandNode(DjangoObjectType):
        # extra field INT
        extra_field_real_id_plus_one = graphene.Int()
    
        def resolve_extra_field_real_id_plus_one(parent, info, **kwargs):
            value = parent.id + 1
            print(f'Real Id: {parent.id}')
            print(f'Id ++: {value}')
            return value
    
        class Meta:
            model = Brand
            filter_fields = {
                'name': ['icontains', 'exact']
            }
            interfaces = (relay.Node,)
    

    extra_field_real_id_plus_one 是额外的字段。您可以从原始模型中获取任何值,完全来自 parent 参数。你可以计算或格式化任何你想要的,只需要返回值。 您可以在查询、突变等中获取额外的字段计算值。

    【讨论】:

      【解决方案2】:

      Graphene 使用 Types 来解析节点,这些节点与模型完全无关,您甚至可以定义一个不与任何模型关联的 Graphene Type。无论如何,您正在寻找的用例非常简单。假设我们有一个模型名称 User,我假设这个 Data 需要由模型的解析器解析。

      from graphene.relay import Node
      from graphene import ObjectType, JSONField, String
      from graphene_django import DjangoObjectType
      
      from app.models import User
      
      class UserType(DjangoObjectType):
          class Meta:
              filter_fields = {'id': ['exact']}
              model = User
      
          custom_field = JSONField()
          hello_world = String()
      
          @staticmethod
          def resolve_custom_field(root, info, **kwargs):
              return {'msg': 'That was easy!'} # or json.dumps perhaps? you get the idea
      
          @staticmethod
          def resolve_hello_world(root, info, **kwargs):
              return 'Hello, World!'
      
      
      class Query(ObjectType):
          user = Node.Field(UserType)
          all_users = DjangoFilterConnectionField(ProjectType)
      

      【讨论】:

      • 使用custom_field = GenericScalar() 代替custom_field = JSONField() 并导入from graphene.types.generic import GenericScalar
      猜你喜欢
      • 2018-02-21
      • 2021-08-06
      • 2019-12-20
      • 2020-08-11
      • 2019-04-03
      • 2019-11-30
      • 2018-01-11
      • 2020-09-01
      • 2021-09-25
      相关资源
      最近更新 更多