【问题标题】:Graphene Django: Change field names石墨烯 Django:更改字段名称
【发布时间】:2019-04-03 15:37:23
【问题描述】:

如果我有一个 Django 模型,其法语字段名称是这样的(nomname 的法语翻译):

class Categorie(models.Model):
    nom = models.CharField(max_length=100)

    def __str__(self):
        return self.nom

是否可以使用 Graphene Django 配置 GraphQL 查询,以便使用字段的英文翻译查询图形(使用 name 而不是 nom):

query {
  allCategories {
    id
    name
  }
}  

谢谢,

【问题讨论】:

    标签: django graphql graphene-python


    【解决方案1】:

    当你定义你的DjangoObjectType 试试这个:

    class CategorieType(DjangoObjectType):
        name = graphene.String()
    
        class Meta:
            model = Categorie
            exclude_fields = ('nom',)  # Do this only if you want to HIDE "nom"
    
        def resolve_name(self, info):
            return self.nom
    

    【讨论】:

    • 请注意,您需要解析器的第二个info 参数才能使其工作。 IE。 def resolve_name(self, info):.
    • 我们如何返回 ID 而不是 id
    • 对“名称”字段遵循相同的模式,如图所示,除了 ID 的字段类型应该是 id 字段的类型,大概是 graphene.Int()
    猜你喜欢
    • 2018-01-11
    • 2020-09-01
    • 2020-08-11
    • 2020-08-18
    • 2019-12-20
    • 2021-09-25
    • 2020-09-05
    • 2017-08-20
    • 2020-09-03
    相关资源
    最近更新 更多