You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django工具函数优化:合并重复逻辑实现通用唯一ID生成器

Refactor Duplicate Unique ID Generators into a Single Reusable Function

Got it, let's clean up those duplicate functions into one flexible unique_id_generator that lets you specify the filter field when calling it. Here's a clean, DRY (Don't Repeat Yourself) implementation:

import random
import string

def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def unique_id_generator(instance, _filter, size=10):
    # Generate initial random ID
    new_id = random_string_generator(size=size)
    
    # Dynamically build filter query using the specified field
    # Using a dictionary + ** unpacking lets us use any field name passed in
    query_set = instance.__class__.objects.filter(**{_filter: new_id})
    
    # Keep generating new IDs until we find one that doesn't exist in the database
    while query_set.exists():
        new_id = random_string_generator(size=size)
        query_set = instance.__class__.objects.filter(**{_filter: new_id})
    
    return new_id

Key Notes:

  • Dynamic Filtering: The {_filter: new_id} dictionary unpacked with ** is what makes this function flexible. It lets you pass any field name (like slug or order_id) to use as the uniqueness check.
  • Consolidated Logic: All the duplicate code from your two original functions is now in one place—no more repeating the random string generation or existence check logic.
  • Optional Size Parameter: We kept the size argument optional so you can adjust the length of the generated ID if needed for different use cases.

How to Call It:

  • For a unique account link slug:
    unique_slug = unique_id_generator(account_instance, _filter="slug")
    
  • For a unique order ID:
    unique_order_id = unique_id_generator(order_instance, _filter="order_id")
    

This setup makes it easy to add support for other unique fields later too—just pass the field name when calling the function.

内容的提问来源于stack exchange,提问作者user9252255

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:34:24