Randomize Column Names in Peewee Model

  • Share this:

Code introduction


This function uses the Peewee library to accept a Peewee model table and return a new table with randomly generated column names.


Technology Stack : Peewee

Code Type : Function

Code Difficulty : Intermediate


                
                    
def randomize_column_names(table):
    """
    This function takes a Peewee model table and returns a new table with randomly generated column names.
    """
    import random
    from peewee import Model, Field

    # Define a new model with the same fields but with random names
    class RandomizedTable(Model):
        random_col1 = Field()
        random_col2 = Field()
        random_col3 = Field()

    # Map original field names to random names
    field_mapping = {field.name: f"random_col{i+1}" for i, field in enumerate(table._meta.fields)}

    # Create a new model with randomized field names
    RandomizedTable._meta.fields = [Field(field_mapping[field.name], field.type) for field in table._meta.fields]
    
    return RandomizedTable                
              
Tags: