如何实现Django模型到grapheneDjango类型的自定义映射?

2024-06-26 13:36:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: djangofrompy模型importappnanomodels