简体   繁体   中英

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. So for example I got 3 datarecords and two have an attribute name = Max and the last one has the attribute name = Peter . How can I now delete both Max's? 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?

Just remove the .first() method and add delete to the query itself

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

'''
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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