SQL:未映射类。未映射NoneType

sqlalchemy.orm.exc.UnmappedInstanceError: Class #39;builtins.NoneType#39; is not mapped(SQL:未映射类。未映射NoneType)
本文介绍了SQL:未映射类。未映射NoneType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个SQLALCHEMIY模型设置,它们都是一对多关系。用户模型包含多个任务模型,任务模型包含多个子任务模型。当我执行test_script.py时,我收到错误sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.NoneType' is not mapped

我已经阅读并尝试了每个模块上的一些不同关系。我的目标是能够在用户和任务模型中拥有包含其正确子级的列表。我最终希望访问列表项,如user_x.task[3].subtask[1]

代码如下: (型号、脚本、错误)

型号

class User(Base):
    """ User Model for storing user related details """
    __tablename__ = 'Users'

    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    username = Column(String(255), nullable=False)
    password_hash = Column(String(128), nullable=False)
    email = Column(String(255), nullable=False, unique=True)
    created_date = Column(DateTime, default=datetime.utcnow)

    tasks = relationship(Task, backref=backref("Users", uselist=False))

    def __init__(self, username: str, password_hash: str, email: str):
        self.username = username
        self.password_hash = password_hash
        self.email = email



class Task(Base):
    """ Task Model for storing task related details """
    __tablename__ = 'Tasks'

    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    title = Column(String(255), nullable=False)
    folder_name = Column(String(255), nullable=True)
    due_date = Column(DateTime, nullable=True)
    starred = Column(Boolean, default=False)
    completed = Column(Boolean, default=False)
    note = Column(String, nullable=True)
    created_date = Column(DateTime, default=datetime.utcnow)
    user_id = Column(Integer, ForeignKey('Users.id'))

    subtasks = relationship(Subtask, backref=backref("Tasks", uselist=False))

    def __init__(self, title: str, **kwargs):
        self.title = title
        self.folder_name = kwargs.get('folder_name', None)
        self.due_date = kwargs.get('due_date', None)
        self.starred = kwargs.get('starred', False)
        self.completed = kwargs.get('completed', False)
        self.note = kwargs.get('note', None)



class Subtask(Base):
    """ Subtask Model for storing subtask related details """
    __tablename__ = 'Subtasks'

    id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
    title = Column(String(255), nullable=False)
    completed = Column(Boolean, default=False)
    task_id = Column(Integer, ForeignKey('Tasks.id'))

    def __init__(self, title: str, **kwargs):
        self.title = title
        self.completed = kwargs.get('completed', False)

test_script.py

session1 = create_session()

user1 = User(
    username="Stephen",
    password_hash="p-hash",
    email="stephen@gmail.com"
).tasks.append(
    Task(
        title='Delete Me',
        folder_name='Folder 1'
    ).subtasks.append(
        Subtask(
            title='Delete Me 2'
        )
    )
)

session1.add(user1)

session1.commit()
session1.close()

错误消息

/Users/StephenCollins/Respositories/pycharm_workspace/Personal/BusyAPI_v1/venv/bin/python /Users/StephenCollins/Respositories/pycharm_workspace/Personal/BusyAPI_v1/tests/test_script.py
Traceback (most recent call last):
  File "/Users/StephenCollins/Respositories/pycharm_workspace/Personal/BusyAPI_v1/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1943, in add
    state = attributes.instance_state(instance)
AttributeError: 'NoneType' object has no attribute '_sa_instance_state'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/StephenCollins/Respositories/pycharm_workspace/Personal/BusyAPI_v1/tests/test_script.py", line 24, in <module>
    session1.add(user1)
  File "/Users/StephenCollins/Respositories/pycharm_workspace/Personal/BusyAPI_v1/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1945, in add
    raise exc.UnmappedInstanceError(instance)
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.NoneType' is not mapped

希望我接近了,但如果我完全走错了方向,请让我知道。我在之前的实习中用过一点Hibernate,但我是自学的(最好的一种),在Python、SqlalChemy和MySQL方面。

推荐答案

在原地更改对象的方法中,通常返回None。赋值的表达式链接创建模型对象,访问关系属性,并附加到所述属性,这将返回None。拆分操作:

user1 = User(
    username="Stephen",
    password_hash="p-hash",
    email="stephen@gmail.com"
)

task1 = Task(
    title='Delete Me',
    folder_name='Folder 1'
)

task1.subtasks.append(
    Subtask(
        title='Delete Me 2'
    )
)

user1.tasks.append(task1)

这篇关于SQL:未映射类。未映射NoneType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)