Random Record Selector for Database Models

  • Share this:

Code introduction


This function randomly selects a record from a database model. It accepts a database session and a model class as parameters, and returns a randomly selected record.


Technology Stack : SQLAlchemy

Code Type : Database Query Function

Code Difficulty : Intermediate


                
                    
def random_select(session, model):
    import random
    from sqlalchemy import func

    # Randomly select a record from the model
    random_record = session.query(model).order_by(func.random()).first()
    return random_record                
              
Tags: