2021.01.08
● PUBLIC
AttributeError: 'Options' object has no attribute 'name'
graphqlpythondjango
SYMPTOMS
Faulty code:
# models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
# schema/author.py
import graphene
from graphene_django import DjangoObjectType
from .models import Author
class AuthorType(DjangoObjectType):
class Meta:
model = Author
fields = "__all__"
When splitting the main schema into files, this errors occurred when opening graphql editor:
AttributeError: 'Options' object has no attribute 'name'
FIX
The fix was simple — instead of:
# models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
# schema/author.py
import graphene
from graphene_django import DjangoObjectType
from .models import Author
class AuthorType(DjangoObjectType):
class Meta:
model = Author
fields = "__all__"
I had to import graphene_django.types.DjangoObjectType and use it as a base class:
# schema/author.py
import graphene
from graphene_django.types import DjangoObjectType # <- Import from here
from .models import Author
class AuthorType(DjangoObjectType):
class Meta:
model = Author
fields = "__all__"
TAKEAWAY: Always import
graphene_django.types.DjangoObjectTypeinstead of usingDjangoObjectTypedirectly when splitting Graphene schemas into files.