石墨烯突变未映射 SQLAlchemy 中的模型
Posted
技术标签:
【中文标题】石墨烯突变未映射 SQLAlchemy 中的模型【英文标题】:Graphene mutation not mapping Models in SQL Alchemy 【发布时间】:2017-08-25 14:41:09 【问题描述】:我正在尝试对使用 SQL ALCHEMY 声明的用户模型执行突变。 这是我的 models.py 文件的代码
# blog/models.py
from sqlalchemy import *
from sqlalchemy.orm import (scoped_session, sessionmaker, relationship,
backref)
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///database.sqlite3', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
# We will need this for querying
Base.query = db_session.query_property()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key= True)
name = Column(String)
email = Column(String)
posts = relationship("Post", backref="user")
class Post(Base):
__tablename__ = 'post'
id = Column(Integer, primary_key= True)
title = Column(String)
text = Column(Text)
user_id = Column(Integer, ForeignKey('user.id'))
这是 Schema.py 文件
import graphene
from graphene import relay
from graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField
from models import db_session,User as UserModel, Post as PostModel
from sqlalchemy import *
class User(SQLAlchemyObjectType):
class Meta:
model = UserModel
interfaces = (relay.Node, )
class Post(SQLAlchemyObjectType):
class Meta:
model = PostModel
interfaces = (relay.Node, )
class CreateUser(graphene.Mutation):
class Input:
name = graphene.String()
ok = graphene.Boolean()
user = graphene.Field(User)
@classmethod
def mutate(cls, instance, args, context, info):
new_user = User(name=args.get('name'))
db_session.add(new_user)
db_session.commit()
ok = True
return CreateUser(user=new_user, ok=ok)
class Query(graphene.ObjectType):
node = relay.Node.Field()
user = relay.Node.Field(User)
allUsers = SQLAlchemyConnectionField(User)
class MyMutations(graphene.ObjectType):
create_user = CreateUser.Field()
schema = graphene.Schema(query=Query, mutation = MyMutations, types = [User, Post])
当我尝试执行以下突变时,这是我得到的错误:
--Query--
mutation Test
createUser(name:"tess")
ok
user
name
--Result--
"errors": [
"message": "Class 'schema2.User' is not mapped",
"locations": [
"line": 2,
"column": 3
]
],
"data":
"createUser": null
【问题讨论】:
【参考方案1】:您正在尝试使用错误的类创建用户。当您调用 User(name=args.get('name'))
行时,您的意思似乎是 UserModel错误是正确的,SQLAlchemyObjectType 用户未映射,您作为 UserModel 导入的模型用户是。
【讨论】:
谢谢,我真的很想念。花了几个小时找出问题所在。以上是关于石墨烯突变未映射 SQLAlchemy 中的模型的主要内容,如果未能解决你的问题,请参考以下文章