gpt4 book ai didi

Django 与 Graphite 烯 : How to handle bidirectional relationship with polmorphic models?

转载 作者:行者123 更新时间:2023-12-02 09:57:17 25 4
gpt4 key购买 nike

我有一个看起来像这样的 Django 模型(当然是简化的):

from django.db import models
from polymorphic.models import PolymorphicModel

class Tournament(models.Model):
slug = models.CharField(max_length=100, unique=True)

class Event(PolymorphicModel):
tournament = models.ForeignKey(Tournament, related_name='events')
slug = models.CharField(max_length=100)

class PracticeEvent(Event):
pass

class MatchEvent(Event):
winner = models.CharField(max_length=100, null=True, blank=True, default=None)

锦标赛包括两种类型的赛事:练习赛和比赛。我想使用 GraphQL、使用 Graphene 来公开这个模型。这是我想到的:

import graphene
from graphene_django import DjangoObjectType

from . import models

class TournamentType(DjangoObjectType):
class Meta:
model = models.Tournament
exclude_fields = ('id',)

class EventType(graphene.Interface):
tournament = graphene.Field(TournamentType, required=True)
slug = graphene.String(required=True)

class PracticeEventType(DjangoObjectType):
class Meta:
model = models.PracticeEvent
interfaces = (EventType,)
exclude_fields = ('id',)

class MatchEventType(DjangoObjectType):
class Meta:
model = models.MatchEvent
interfaces = (EventType,)
exclude_fields = ('id',)

extra_types = {PracticeEventType, MatchEventType}

class Query(graphene.ObjectType):
tournaments = graphene.List(TournamentType)
events = graphene.List(EventType)
# ... resolvers ...

schema = graphene.Schema(
query=Query,
types=schema_joust.extra_types,)

到目前为止,一切顺利;我可以直接查询events { ... },甚至锦标赛也可用。但是,由于 model = models.Event 中没有 DjangoObjectType,因此我无法查询 tournaments { events {...} }。 ..

我该如何解决这个问题?我无法将 EventType 设为 DjangoObjectTpe,并且我不知道在事后添加 events 字段。

最佳答案

靠自己,EventType.tournamentTournamentType.events没那么难。第一个如问题所示,第二个可以这样实现:

class EventType(graphene.Interface):
slug = graphene.String(required=True)

class TournamentType(DjangoObjectType):
class Meta:
model = models.Tournament
exclude_fields = ('id',)

events = graphene.List(EventType)

def resolve_events(self, info):
return self.events.all()

graphene-django 无法识别这种关系,但手动声明和解析该字段可以解决问题。还可以获得反向字段,如果我们不需要引用TournamentType,这将起作用。 ,我深入研究 graphene-django 并发现 graphene_django.converter.convert_django_field_with_choices 。这让我们可以像这样定义字段:

import graphene
from graphene_django import DjangoObjectType, converter, registry

from . import models

class EventType(graphene.Interface):
tournament = converter.convert_django_field_with_choices(
models.Event.tournament.field, registry.get_global_registry())
slug = graphene.String(required=True)

关于 Django 与 Graphite 烯 : How to handle bidirectional relationship with polmorphic models?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49562532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com