Python 如何实现django模型到graphene django类型的自定义映射?
在Django 3.0.2中,我在Python 如何实现django模型到graphene django类型的自定义映射?,python,django,django-models,graphql,graphene-django,Python,Django,Django Models,Graphql,Graphene Django,在Django 3.0.2中,我在/model.py中定义了如下模型: from django.db import models from django.utils.translation import gettext_lazy as _ class Something(models.Model): class UnitPrefix(models.TextChoices): MILLI = 'MILLI', _('Milli') MICRO = 'M
/model.py
中定义了如下模型:
from django.db import models
from django.utils.translation import gettext_lazy as _
class Something(models.Model):
class UnitPrefix(models.TextChoices):
MILLI = 'MILLI', _('Milli')
MICRO = 'MICRO', _('Micro')
NANO = 'NANO', _('Nano')
class UnitSi(models.TextChoices):
VOLUME = 'CM', _('Cubicmetre')
METRE = 'M', _('Metre')
unit_prefix = models.CharField(
max_length=5,
choices=UnitPrefix.choices,
default=UnitPrefix.MICRO,
)
unit_si = models.CharField(
max_length=2,
choices=UnitSi.choices,
default=UnitSi.M,
)
from graphene_django import DjangoObjectType
from .models import Something
class SomethingType(DjangoObjectType):
class Meta:
model = Something
class Query(object):
"""This object is combined with other app specific schemas in the Django project schema.py"""
somethings = graphene.List(SomethingType)
...
我正在使用graphene django实现GraphQL API。API通过/schema.py
提供模型:
from django.db import models
from django.utils.translation import gettext_lazy as _
class Something(models.Model):
class UnitPrefix(models.TextChoices):
MILLI = 'MILLI', _('Milli')
MICRO = 'MICRO', _('Micro')
NANO = 'NANO', _('Nano')
class UnitSi(models.TextChoices):
VOLUME = 'CM', _('Cubicmetre')
METRE = 'M', _('Metre')
unit_prefix = models.CharField(
max_length=5,
choices=UnitPrefix.choices,
default=UnitPrefix.MICRO,
)
unit_si = models.CharField(
max_length=2,
choices=UnitSi.choices,
default=UnitSi.M,
)
from graphene_django import DjangoObjectType
from .models import Something
class SomethingType(DjangoObjectType):
class Meta:
model = Something
class Query(object):
"""This object is combined with other app specific schemas in the Django project schema.py"""
somethings = graphene.List(SomethingType)
...
结果是我可以通过GraphQL成功查询:
{
somethings {
unitPrefix
unitSi
}
}
但是,我想定义一个GraphQL类型
type Something {
unit: Unit
}
type Unit {
prefix: Unit
si: Si
}
enum UnitPrefix {
MILLI
MICRO
NANO
}
enum UnitSi {
CUBICMETRE
LITRE
}
我可以通过
{
somethings {
unitPrefix
unitSi
}
}
如何实现此自定义模型到类型的映射