3

In Django 3.0.2 I've defined a model like the following one in <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,
    )

I'm using graphene-django to implement a GraphQL API. The API provides the model via <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)
    ...

The result is that I can successfully query via GraphQL:

{
  somethings {
    unitPrefix
    unitSi
  }
}

However I'd like to define a GraphQL type

type Something {
  unit: Unit
}

type Unit {
  prefix: Unit
  si: Si
}

enum UnitPrefix {
  MILLI
  MICRO
  NANO
}

enum UnitSi {
  CUBICMETRE
  LITRE
}

that I can query via

{
  somethings {
    unitPrefix
    unitSi
  }
}

How can I implement this custom model to type mapping?

thinwybk
  • 4,193
  • 2
  • 40
  • 76

0 Answers0