如何将模型默认值设置为函数返回的结果?
How to set model default value to a result bring returned by a function?
我的 model 中有一个 function,它为 model 字段[=生成一个随机值44=],我需要将该值设置为模型字段的默认值。
我有以下模型
class Info(TimeStampedModel):
info_id = models.UUIDField(primary_key=True)
generated_url = models.TextField(
null=False, blank=False, default=random
)
def random(self):
return 'customer.random.domain.com.' + ("".join(random.choices(string.ascii_uppercase + string.digits, k=5)))
我希望 generated_url 的 默认值 来自 方法 在 model 中命名为 random.
但我在运行时得到以下异常:
TypeError: random() missing 1 required positional argument: 'self'
如果我在函数的末尾添加圆括号 name as
generated_url = models.TextField(
null=False, blank=False, default=random()
)
然后在那种情况下我得到一个 compile 时间错误作为 same:
TypeError: random() missing 1 required positional argument: 'self'
所以在阅读了完整的堆栈跟踪之后,我能够弄清楚在我的一个 migrations 中我定义了 random()作为 模型 class 中的函数,属性 generated_uri 指向 内部方法 所以当我试图将 random() 的范围从 class 内部更改为 class 外部时,我遇到了一个异常这是来自 migrations attribute random() is not found in part of the object 所以我的问题的解决方案是。
- 还原所有迁移
- 删除 class 函数更改其范围并将其放在 class
之外
- 再次添加迁移
- 运行 迁移成功了
我的 model 中有一个 function,它为 model 字段[=生成一个随机值44=],我需要将该值设置为模型字段的默认值。
我有以下模型
class Info(TimeStampedModel):
info_id = models.UUIDField(primary_key=True)
generated_url = models.TextField(
null=False, blank=False, default=random
)
def random(self):
return 'customer.random.domain.com.' + ("".join(random.choices(string.ascii_uppercase + string.digits, k=5)))
我希望 generated_url 的 默认值 来自 方法 在 model 中命名为 random.
但我在运行时得到以下异常:
TypeError: random() missing 1 required positional argument: 'self'
如果我在函数的末尾添加圆括号 name as
generated_url = models.TextField(
null=False, blank=False, default=random()
)
然后在那种情况下我得到一个 compile 时间错误作为 same:
TypeError: random() missing 1 required positional argument: 'self'
所以在阅读了完整的堆栈跟踪之后,我能够弄清楚在我的一个 migrations 中我定义了 random()作为 模型 class 中的函数,属性 generated_uri 指向 内部方法 所以当我试图将 random() 的范围从 class 内部更改为 class 外部时,我遇到了一个异常这是来自 migrations attribute random() is not found in part of the object 所以我的问题的解决方案是。
- 还原所有迁移
- 删除 class 函数更改其范围并将其放在 class 之外
- 再次添加迁移
- 运行 迁移成功了