[英]How to use a django abstract class with graphene-django?
我正在嘗試為兩個相似的具體類提供一個獨特的接口,並從一個公共抽象類繼承。
我的 Django 模型類:
class Metadata(models.Model):
name = models.CharField(max_length=255)
sequence = models.PositiveSmallIntegerField()
is_choices = False
class Meta:
abstract = True
class MetadataScalar(Metadata):
string_format = models.CharField(max_length=255, blank=True, null=True)
class MetadataChoices(Metadata):
is_choices = True
choices = models.CharField(max_length=255, blank=True, null=True)
我的石墨烯-django api:
class MetadataNode(DjangoObjectType):
class Meta:
interfaces = (Node,)
connection_class = Connection
model = Metadata
fields = '__all__'
class MetadataScalarNode(MetadataNode):
class Meta:
interfaces = (Node,)
connection_class = Connection
model = MetadataScalar
fields = '__all__'
class MetadataChoicesNode(MetadataNode):
class Meta:
interfaces = (Node,)
connection_class = Connection
model = MetadataChoices
fields = '__all__'
class CreateMetadata(ClientIDMutation):
metadata = Field(MetadataNode)
class Input:
name = String(max_length=255, required=True)
sequence = Int(required=True)
string_format = String()
choices = List(String)
@classmethod
def mutate_and_get_payload(cls, root, info, **input):
if 'string_format' in input:
metadata = MetadataScalar.objects.create(
name=input.get('name'),
sequence=input.get('sequence'),
string_format=input.get('string_format')
)
elif 'choices' in input:
metadata = MetadataChoices.objects.create(
name=input.get('name'),
sequence=input.get('sequence'),
choices=','.join(input.get('choices'))
)
return CreateMetadata(metadata=metadata)
當查詢到CreateMetadata
對應的 graphql 突變時,成功創建了元數據具體類。 ;-)
問題是,當查詢在結果中要求創建具體的Metadata
(這里是MetadataScalar
或MetadataChoices
)時, graphql找不到具體類的節點並輸出以下錯誤消息:
Expected value of type "MetadataNode" but got: MetadataScalar.
以下是一個示例查詢,供您參考:
mutation {
createMetadata (input: {
stringFormat: "foo"
sequence: 12
name: "bar"
}) {
metadata {
name
sequence
}
}
}
如何讓它很好地工作,而不必在查詢的第二部分指定兩種不同的結果類型( metadataScalar
和metadataChoices
變量)?
您可以使用Union來指定多個不同的結果類。
在您的情況下,那將是:
class MetadataScalarNode(DjangoObjectType):
class Meta:
interfaces = (Node,)
connection_class = Connection
model = MetadataScalar
fields = '__all__'
class MetadataChoicesNode(DjangoObjectType):
class Meta:
interfaces = (Node,)
connection_class = Connection
model = MetadataChoices
fields = '__all__'
class MetadataNode(Union):
class Meta:
types = (MetadataScalarNode, MetadataChoicesNode)
graphql 查詢將如下所示:
mutation {
createMetadata (input: {
stringFormat: "foo"
sequence: 12
name: "bar"
}) {
metadata {
__typename
... on MetadataScalarNode {
name
sequence
stringFormat
}
... on MetadataChoicesNode {
name
sequence
choices
}
}
}
}
你試一試
... on metadata{
name
sequence
}
與您的界面。 Union 不能有任何字段,因此如果使用 Union 與 Interfaces,您需要有重復項。 https://docs.graphene-python.org/en/latest/types/unions/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.