简体   繁体   English

SQLAlchemy删除所有项目,而不仅仅是第一个

[英]SQLAlchemy delete all items and not just the first

I am trying to delete some datarecords from my db. 我正在尝试从数据库中删除一些数据记录。 I made cascade to also delete everything related to the datarecord. 我进行了级联操作,还删除了与数据记录相关的所有内容。 My problem is now that what if I have more than one datarecord with the same name attribute and I want to delete them all. 现在的问题是,如果我有多个具有相同name属性的数据记录,而我想全部删除它们该怎么办。 So for example I got 3 datarecords and two have an attribute name = Max and the last one has the attribute name = Peter . 例如,我有3个数据记录,两个记录的属性name = Max ,最后一个记录的属性name = Peter How can I now delete both Max's? 现在如何删除两个Max? This is the code I got so far: 这是我到目前为止得到的代码:

def delete_anw(engine):
    Session = sessionmaker(bind=engine)
    session = Session()
    f = session.query(Anwendung).filter_by(name="Max").first()
    session.delete(f)
    session.commit()

This code only deletes the first query that it finds. 此代码仅删除找到的第一个查询。 I know it's because of the first() but is there a method like all() to delete all datarecords that have the name Max? 我知道这是由于first()但是有没有像all()这样的方法来删除所有名称为Max的数据记录?

Just remove the .first() method and add delete to the query itself 只需删除.first()方法并向查询本身添加delete

session.query(Anwendung).filter_by(name="Max").delete()

http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.delete Look at this for reference http://docs.sqlalchemy.org/zh-CN/latest/orm/query.html#sqlalchemy.orm.query.Query.delete查看该内容以供参考

'''
Created on 2017年10月24日

@author: leemengwei
'''

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column,Integer,String
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()

class Anwendung(Base):
    __tablename__ = 'tab1'

    id = Column(Integer, primary_key=True)
    name = Column(String)


def delete_anw():
    session = Session()
    f = session.query(Anwendung).filter_by(name="Max").delete()
    print('records deleted:',f)
    session.commit()
    session.close()

def query_anw():
    session = Session()
    f = session.query(Anwendung).filter_by(name="Max").all()
    print('records matched:',len(f))
    session.close()

if __name__=='__main__':
    engine = create_engine("mysql+pymysql://root@localhost/test",echo=True)
    Session = sessionmaker(bind=engine)

    query_anw()
    delete_anw()
    query_anw()

The code above works fine for me.The records are found and deleted. 上面的代码对我来说很好用。找到并删除了记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM