SQLAlchemy删除所有重复的用户|Counter类运用

Python标准库中的collections模块中的Counter类。Counter类用于计算可迭代对象中元素的出现次数,并以字典的形式返回结果,其中键是元素,值是该元素的出现次数。

for name, count in Counter(names).items() 是一个循环语句,它用于遍历Counter对象的所有项。

在这个循环中,Counter(names).items() 返回一个包含键-值对的元组的列表,其中键是用户名,值是该用户名在names列表中出现的次数。例如,如果有两个用户具有相同的用户名,那么它们的用户名在names列表中就会出现两次。

因此,for name, count in Counter(names).items() 遍历了这个键-值对列表,并将键赋值给name,将值赋值给count,以便在循环体内使用。

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import relationship, sessionmaker

# 创建数据库连接和会话
engine = create_engine('sqlite:///usersexample.db')
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()

# 定义模型
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String, unique=True)  # 添加了唯一性约束
    profile = relationship('UserProfile', uselist=False, backref='user')

class UserProfile(Base):
    __tablename__ = 'user_profiles'
    id = Column(Integer, primary_key=True)
    bio = Column(String)
    user_id = Column(Integer, ForeignKey('users.id'))

# 创建表格
Base.metadata.create_all(engine)

# 创建10个用户
users_data = [
    {"name": "Alice", "bio": "I'm a software engineer."},
    {"name": "Bob", "bio": "I love hiking."},
    {"name": "Charlie", "bio": "Music is my passion."},
    {"name": "David", "bio": "I'm a foodie."},
    {"name": "Eve", "bio": "I'm a bookworm."},
    {"name": "Frank", "bio": "I'm a fitness enthusiast."},
    {"name": "Grace", "bio": "I'm a photographer."},
    {"name": "Hank", "bio": "I'm a travel blogger."},
    {"name": "Ivy", "bio": "I'm a painter."},
    {"name": "Jack", "bio": "I'm a movie buff."}
]

# 创建用户之前先检查数据库中是否已存在相同名称的用户
for user_data in users_data:
    user = session.query(User).filter_by(name=user_data["name"]).first()
    if user is None:
        user = User(name=user_data["name"])
        profile = UserProfile(bio=user_data["bio"])
        user.profile = profile
        session.add(user)

# 提交事务
session.commit()

# 查询功能丰富示例
# 查询所有用户及其用户资料
all_users = session.query(User).all()
for user in all_users:
    print(f"User {user.name}: {user.profile.bio}")

# 查询特定用户的用户资料
specific_user = session.query(User).filter(User.name == 'Alice').first()
if specific_user:
    print(f"User {specific_user.name}: {specific_user.profile.bio}")

# 其他数据库操作示例
# 更新用户资料
specific_user.profile.bio = "I'm a data scientist."
session.commit()

# 查找并删除重复的用户
from collections import Counter

# 找出所有重复的用户
names = [user.name for user in all_users]
duplicate_names = [name for name, count in Counter(names).items() if count > 1]

# 删除所有重复的用户
for name in duplicate_names:
    duplicate_users = session.query(User).filter(User.name == name).all()
    for user in duplicate_users[1:]:
        session.delete(user)

# 提交事务
session.commit()

# 关闭会话
session.close()

你可能感兴趣的:(oracle,数据库,python)