2

在 Django 3.0.2 中,我定义了一个模型,如下所示<django-app>/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,
    )

我正在使用 graphene-django 来实现 GraphQL API。API 通过以下方式提供模型<django-app>/schema.py

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

如何实现此自定义模型到类型映射?

4

0 回答 0