无法使用 delete() 从数据库中删除对象
Posted
技术标签:
【中文标题】无法使用 delete() 从数据库中删除对象【英文标题】:Deleting an object from the database with delete() not possible 【发布时间】:2020-09-22 12:39:33 【问题描述】:根据文档,应该有delete()方法(https://docs.sqlalchemy.org/en/13/core/tutorial.html#deletes),但是我的模型好像没有delete()方法,我做错了什么?
模型.py
>from sqlalchemy import BigInteger, Column, DateTime, ForeignKey, Integer, Numeric, String, Text, text
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class Category(Base):
__tablename__ = 'category'
id = Column('id', Integer, primary_key=True)
name = Column('name', String(200))
parentid = Column('parentid', Integer)
Main.py
> def crud_delete_single_cat(db: Session, cat_id: int) -> int:
query = models.Category.delete().where(models.Category.id == cat_id)
print(query)
results = db.query()
return results.rowcount
我尝试运行该方法时的错误消息:
AttributeError: type object 'Category' has no attribute 'delete'
【问题讨论】:
docs.sqlalchemy.org/en/13/core/tutorial.html#deletes 他们的例子是从类 sqlalchemy.Table 生成的对象。您正在使用不同的类,因此您正在查看错误的辅助文档或正在以没有.delete()
的不同方式实现它。
是models.Category.__table__.delete().where(...)
,根据***.com/a/39774354/683329 吗?
使用 ORM 时,通过会话删除:session.delete(model_instance)
。
【参考方案1】:
感谢您的回答,我发现了错误并修复了它,我改变了创建模型的方式。我使用了文档中的“经典映射”,现在正在删除作品:)
模型.py
>from sqlalchemy import BigInteger, Column, DateTime, ForeignKey, Integer, Numeric, String, Text, text, Table
from sqlalchemy.orm import relationship, mapper
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
category = Table('category', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(200)),
Column('parentid', Integer),
)
class Category(object):
def __init__(self, cat_id, name, parentid):
self.id = cat_id
self.name = name
self.parentid = parentid
mapper(Category, category)
main.py
>def crud_delete_single_cat(db: Session, cat_id: int) -> bool:
# records = db.query(models.Category).all()
stm = models.category.delete().where(models.category.c.id == cat_id)
print(stm)
results = db.execute(stm)
db.commit()
# result_set = db.execute("SELECT id, name, parentid FROM public.category;")
# rint(type(result_set))
# for r in result_set:
# print(r)
# return [column: value for column, value in rowproxy.items() for rowproxy in result_set]
# return await databasehelper.database.fetch_all(query)
return True
@router.delete("/category/cat_id", tags=["category"])
def read_item(cat_id: int, db: Session = Depends(get_db)):
deleted = crud_delete_single_cat(db, cat_id)
return "cat_deleted": deleted
【讨论】:
以上是关于无法使用 delete() 从数据库中删除对象的主要内容,如果未能解决你的问题,请参考以下文章
Flutter parse-server sdk 无法删除对象