2017-01-27 34 views
1

我正在與graphenegraphene-django一起工作,我有一個IntegerField有問題的選項。 graphene創建Enum,如果值爲1,則輸出爲「A_1」;如果值爲2等等,則爲「A_2」。例如:覆蓋石墨烯中的django選項輸出

# model 
class Foo(models.Model): 
    score = models.IntegerField(choices=((1, 1), (2, 2), (3, 3), (4, 4), (5, 5))) 

# query 

query { 
    foo { 
     score 
    } 
} 

# response 

{ 
    "data": { 
    "foo": { 
     "source": "A_1" 
    } 
    } 
} 

我找到了一個函數來轉換選項值。

def convert_choice_name(name): 
    name = to_const(force_text(name)) 
    try: 
     assert_valid_name(name) 
    except AssertionError: 
     name = "A_%s" % name 
    return name 

而且assert_valid_name有這樣的正則表達式:

r'^[_a-zA-Z][_a-zA-Z0-9]*$' 

因此,無論用數字開頭,將其轉換爲 「A _...」。

我如何覆蓋這個輸出?

回答

1

代碼中的註釋說

GraphQL序列化枚舉值作爲字符串,但在內部枚舉 可以通過任何一種類型,通常整數表示。

因此,對於您的特定情況,您將無法輕鬆地用整數替換整數值。但是,如果由字符串(「A_1」)表示的實際值在內部和客戶端(來自字段的描述值)仍然是整數,則可能無關緊要。

通常,雖然可以將自動生成的字段通過定義一個枚舉類並添加到DjangoObjectType的定義來爲該字段提供選擇。下面是使用的文檔例如枚舉的例子...

class Episode(graphene.Enum): 
    NEWHOPE = 4 
    EMPIRE = 5 
    JEDI = 6 

    @property 
    def description(self): 
     if self == Episode.NEWHOPE: 
      return 'New Hope Episode' 
     return 'Other episode' 

然後你可以添加到您的DjangoObjectType

class FooType(DjangoObjectType): 
    score = Episode() 
    class Meta: 
     model = Foo 

或者,如果你想獲得額外看上你可以從動態生成的枚舉場您的領域在Foo._meta.get_field('score').choices的選擇。見graphene_django.converter.convert_django_field_with_choices