使用模型数据的 Django 模型方法

Django Model method that uses data from the model

我想生成唯一代码(例如“DXGH”)并将其保存为我的一个模型中的一个字段。我遇到的问题是,每当创建新对象时,我不知道如何检查以前生成的代码。

目前我的 models.py 看起来像这样:

def code_gen():
    random_string = ''
    for _ in range(4):
        random_string += chr(random.randint(97,122))
    return random_string

class Room(models.Model):
    room_code = models.CharField(default=code_gen)
    #other fields

    def __str__(self):
        return self.room_code

    #other methods

    def code_gen_unique(self):
        #I know the code below is incorrect
        code_list = []
        for object in Room.Objects.all():
            code_list.append(object.room_code)
        while True:
            temp_code = code_gen()
            if temp_code in code_list:
                continue
            break
        return temp_code

理想情况下,我会将 room_code 的默认值设置为 code_gen_unique,但我不能在我之前声明 code_gen_unique()房间 class,也不在它之后。

我希望有一个比我考虑的更简单的解决方案,非常感谢任何帮助!干杯


编辑

感谢 Willem Van Onsem 纠正我的理解 - 在模型之前声明唯一性检查函数,并将该函数设置为 room_code 字段的默认值即可完成工作。

您可以在定义 Room class:

之前 定义默认生成器
def code_gen():
    random_string = ''
    for _ in range(4):
        random_string += chr(random.randint(97,122))
    return random_string

def code_gen_unique():
    code_set = <strong>set(</strong>Room.Objects.values('room_code')<strong>)</strong>
    while True:
        temp_code = code_gen()
        if temp_code not in code_set:
            return temp_code

class Room(models.Model):
    room_code = models.CharField(<strong>default=code_gen</strong>)
    
    # …

Room 标识符将解析为 Room class,因为该方法在定义时不会 运行,但在调用时,它只会被在构建新的 Room 对象时调用。