Python 石墨烯处理多对多关系

Python Graphene working with many to many relations

如果在其他地方回答了这个问题,那么我很抱歉,但下班后 2 天仍然没有雪茄......

我有一个播放器模型:

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
      }
    }
  }
}

其中已知的事实只是基于事实 object.

的多对多关系

到目前为止我创建的 returns 数据但没有根据玩家过滤事实 parent 只显示与 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()

玩家模式:

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)

因此,对于仍在阅读的任何人,我设法通过创建 '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 对它们进行分组,同样的结果来自另一方...