如果在其他地方回答了这个问题,那么我很抱歉,但是下班后两天仍然没有雪茄……
我有一个播放器模型:
class Player(models.Model):
name = models.CharField(max_length=60)
discord_id = models.CharField(max_length=60, null=True)
known_npcs = models.ManyToManyField(NPC)
玩家可以认识很多NPC,并且任何NPC都可以被很多玩家认识。
NPC没什么特别的:
class NPC(models.Model):
image = models.ImageField()
name = models.CharField(max_length=50)
description = models.TextField()
难题的最后一部分是事实,事实是与NPC相关的某些信息,但是一个人可以知道NPC,但不一定与玩家有关的事实都与NPC有关,因此事实看起来像这样:
class Fact(models.Model):
fact = models.TextField()
known_by = models.ManyToManyField(Player)
npc = models.ForeignKey(NPC, on_delete=models.DO_NOTHING, null=True)
现在在石墨烯中,我想创建一个Player和allPlayers查询,这将为我提供:
{
allPlayers {
name
knownNPCs {
image
name
description
factsKnown {
fact
}
}
}
}
已知事实仅仅是基于Fact对象中的ManyToMany关系的事实。
到目前为止,我创建的内容返回了数据,但未根据玩家父级过滤事实,仅显示了与npc相关的所有事实:(
事实架构
class FactType(DjangoObjectType):
class Meta:
model = Fact
filter_fields = ["id"]
class Query(object):
fact = Node.Field(FactType)
all_Facts = graphene.List(FactType)
def resolve_all_Facts(self, info, **kwargs):
return Fact.objects.all()
NPCSchema
class NPCType(DjangoObjectType):
class Meta:
model = NPCS
class Query(object):
all_NPCs = graphene.Field(NPCType)
facts = graphene.List(FactType)
def resolve_all_NPCs(self, info, **kwargs):
return NPCS.objects.all()
PlayerSchema:
class PlayerType(DjangoObjectType):
class Meta:
model = Player
interfaces = (Node,)
filter_fields = ["id"]
class Query(object):
player = Node.Field(PlayerType)
all_players = graphene.List(PlayerType)
def resolve_all_players(self, info, **kwargs):
return Player.objects.all()
def resolve_player(self, info, **kwargs):
player = Player.objects.filter(id=info.id)
答案 0 :(得分:1)
对于仍然阅读的人,我设法通过创建“ filteredFacts”字段来解决此问题:
class PlayerType(DjangoObjectType):
class Meta:
model = Player
filter_fields = ["id"]
filtered_facts = graphene.List(FactGroup)
def resolve_filtered_facts(self, info, **kwargs):
groups = defaultdict(list)
facts = self.known_facts.all()
for fact in facts:
groups[fact.npc].append(fact.fact)
grouped_facts = []
for key, value in groups.items():
grouped_facts.append(FactGroup(npc=key, facts=value))
return grouped_facts
这将获得玩家已知的所有事实,并按NPC将其分组,而从另一端得到相同的结果...