Random User Selection and Username Renaming with SQLAlchemy

  • Share this:

Code introduction


The function uses the SQLAlchemy library to randomly select a user from the database and generate a new username in the format 'User_X_Renamed', where X is the original user's ID.


Technology Stack : SQLAlchemy, SQLite, declarative_base, Column, Integer, String, create_engine, Session, func.random(), query, order_by, first()

Code Type : The type of code

Code Difficulty :


                
                    
def generate_random_user_name(session):
    from sqlalchemy import func
    from sqlalchemy.orm import sessionmaker
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, Integer, String

    Base = declarative_base()

    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        name = Column(String)

    # Create an instance of the engine
    engine = create_engine('sqlite:///:memory:')
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)

    # Randomly select a user and generate a new name
    session = Session()
    user = session.query(User).order_by(func.random()).first()
    new_name = f"User_{user.id}_Renamed"
    user.name = new_name
    session.commit()

    session.close()