Django multi-table继承和石墨烯
Django multi-table inheritance and graphene
我正在尝试通过 django-graphene 提供 graphql 端点。我有以下型号:
class BaseModel(models.Model):
fk = models.ForeignKey(MainModel, related_name='bases')
base_info = models.CharField(...)
class ChildModel(BaseModel):
name = models.CharField(...)
MainModel
是我的中央数据模型。 ChildModel
有几种变体,这解释了这里使用的 multi-table 继承。
我已经能够使用这个模式声明来工作:
class BaseModelType(DjangoObjectType):
class Meta:
model = BaseModel
class ChildModelType(DjangoObjectType):
class Meta:
model = ChildModel
class MainModelType(DjangoObjectType):
class Meta:
model = MainModel
允许以下 graphQL 查询:
{
mainModel(id: 123) {
id
bases {
id
baseInfo
childmodel {
id
name
}
}
}
}
但是,我想按照 Django 理解继承的方式将其展平,以便我可以像这样查询数据:
{
mainModel(id: 123) {
id
bases {
id
baseInfo
name <--- this field from the child is now on the base level
}
}
}
我怀疑答案就在我声明的方式中 ChildModelType
,但我一直没弄明白。任何提示表示赞赏!
您可以通过在 BaseModelType
class:
中声明附加字段和解析方法来实现
class BaseModelType(DjangoObjectType):
name_from_child = graphene.String()
class Meta:
model = BaseModel
def resolve_name_from_child(self, info):
# if ChildModel have ForeignKey to BaseModel
# first_child = self.childmodel_set.first()
# for your case with multi-table inheritance
# ChildModel is derived from BaseModel: class ChildModel(BaseModel):
first_child = self.childmodel
if first_child:
return first_child.name
return None
查询:
{
mainModel(id: 123) {
id
bases {
id
baseInfo
name_from_child <--- first child name
}
}
}
我正在尝试通过 django-graphene 提供 graphql 端点。我有以下型号:
class BaseModel(models.Model):
fk = models.ForeignKey(MainModel, related_name='bases')
base_info = models.CharField(...)
class ChildModel(BaseModel):
name = models.CharField(...)
MainModel
是我的中央数据模型。 ChildModel
有几种变体,这解释了这里使用的 multi-table 继承。
我已经能够使用这个模式声明来工作:
class BaseModelType(DjangoObjectType):
class Meta:
model = BaseModel
class ChildModelType(DjangoObjectType):
class Meta:
model = ChildModel
class MainModelType(DjangoObjectType):
class Meta:
model = MainModel
允许以下 graphQL 查询:
{
mainModel(id: 123) {
id
bases {
id
baseInfo
childmodel {
id
name
}
}
}
}
但是,我想按照 Django 理解继承的方式将其展平,以便我可以像这样查询数据:
{
mainModel(id: 123) {
id
bases {
id
baseInfo
name <--- this field from the child is now on the base level
}
}
}
我怀疑答案就在我声明的方式中 ChildModelType
,但我一直没弄明白。任何提示表示赞赏!
您可以通过在 BaseModelType
class:
class BaseModelType(DjangoObjectType):
name_from_child = graphene.String()
class Meta:
model = BaseModel
def resolve_name_from_child(self, info):
# if ChildModel have ForeignKey to BaseModel
# first_child = self.childmodel_set.first()
# for your case with multi-table inheritance
# ChildModel is derived from BaseModel: class ChildModel(BaseModel):
first_child = self.childmodel
if first_child:
return first_child.name
return None
查询:
{
mainModel(id: 123) {
id
bases {
id
baseInfo
name_from_child <--- first child name
}
}
}