How to remove duplicated migration having same content in django

if we created a procedure in django project and then we need to changed variables or any changes in content. then same named procedure duplicates . we need to remove it

0002_remove_whocanapprove_approver_level_and_more

0004_remove_whocanapprove_approver_level_and_more

this 2 are same then remove first one

def extract_sql_content(filepath): """Extract the SQL content from a migration file.""" try: with open(filepath, "r") as f: content = f.read() match = SQL_PATTERN.search(content) if match: return match.group( 0 ) # Return the SQL function definition line except Exception as e: print(f"Error reading file {filepath}: {e}") return None

def get_migration_files(directory): """Return a list of migration files in the directory.""" return [ f for f in os.listdir(directory) if FILE_PATTERN.match(f) ]

def group_by_sql_content(migration_files):

content_groups = defaultdict(list)
for filename in migration_files:
    filepath = os.path.join(DIR, filename)
    sql_content = extract_sql_content(filepath)
    if sql_content:
        content_groups[sql_content].append(filename)
return content_groups

def keep_latest_and_remove_others(content_groups):

for files in content_groups.values():
    if len(files) > 1:
        
        files.sort(reverse=True)
        for old_file in files[1:]:
            old_file_path = os.path.join(DIR, old_file)
            try:
                os.remove(old_file_path)
                print(f"Removed: {old_file}")
            except Exception as e:
                print(f"Error removing file {old_file}: {e}")

def main():

migration_files = get_migration_files(DIR)

content_groups = group_by_sql_content(migration_files)

keep_latest_and_remove_others(content_groups)

if name == "main": main()

Вернуться на верх