我想创建两个现有类型(FirstType和SecondType)的UnionType(graphene.Union),并能够解析此联合类型的查询。
class FirstType(DjangoObjectType):
class Meta:
model = FirstModel
class SecondType(DjangoObjectType):
class Meta:
model = SecondModel
class UnionType(graphene.Union):
class Meta:
types = (FirstType, SecondType)
因此,在这种模式下,我想用[pks]列表中的pk查询FirstType和SecondType的所有对象
query {
all_items(pks: [1,2,5,7]){
... on FirstType{
pk,
color,
}
... on SecondType{
pk,
size,
}
}
}
来自FirstType的PK通常不在SecondType中。
我尝试过以下方法
def resolve_items(root, info, ids):
queryset1 = FirstModel.objects.filter(id__in=pks)
queryset2 = SecondModel.objects.filter(id__in=pks)
return queryset1 | queryset2
但是它给出了一个错误:“无法在两个不同的基本模型上组合查询。”
我希望查询得到以下响应:
{ 'data':
{'all_items':[
{'pk': 1,
'color': blue
},
{'pk': 2,
'size': 50.0
},
...
]}
}
那么解析器应该是什么样子?
答案 0 :(得分:0)
好的,所以我太专心于合并查询集,而我并没有注意到我可以简单地返回一个列表。
因此,以下是可以为我提供所需答案的解决方案:
label_values({__name__=~"metric1|metric2|metric3", service=~"abc.*xyz"}, service)
答案 1 :(得分:0)
有关联合类型的石墨烯文档非常稀疏。这是如何正确执行操作的示例:
from graphene import ObjectType, Field, List, String, Int, Union
mock_data = {
"episode": 3,
"characters": [
{
"type": "Droid",
"name": "R2-D2",
"primaryFunction": "Astromech"
},
{
"type": "Human",
"name": "Luke Skywalker",
"homePlanet": "Tatooine"
},
{
"type": "Starship",
"name": "Millennium Falcon",
"length": 35
}
]
}
class Human(ObjectType):
name = String()
homePlanet = String()
class Droid(ObjectType):
name = String()
primaryFunction = String()
class Starship(ObjectType):
name = String()
length = Int()
class Character(Union):
class Meta:
types = (Human, Droid, Starship)
@classmethod
def resolve_type(cls, instance, info):
if instance["type"] == "Human":
return Human
if instance["type"] == "Droid":
return Droid
if instance["type"] == "Starship":
return Starship
class RootQuery(ObjectType):
result = Field(SearchResult)
def resolve_result(_, info):
return mock_data
然后,对于类似
的查询 query Humans {
result {
episode
characters {
... on Droid {
name
}
... on Starship {
name
}
... on Human {
name
}
}
}
}
它返回正确的结果。