【问题标题】:Django model fields unique=True and default=functionDjango 模型字段 unique=True 和 default=function
【发布时间】:2015-08-11 19:13:21
【问题描述】:

所以我有一个看起来像这样的模型

def create_invite_code():
  return str(uuid.uuid4())[0:8]

class InviteCodes(models.Model): 
  id = models.CharField(max_length = 36, primary_key = True, default=build_uuid)      
  code = models.CharField(max_length=8, unique=True, default=create_invite_code)

如果 create_invite_code 返回一个已经存在于数据库中的代码会发生什么,django 会再次调用该函数直到找到一个不存在的代码吗?还是会出错?

【问题讨论】:

  • Python 将引发IntegrityError: UNIQUE constraint failed。在您的create_invite_code 函数中返回常量字符串并自行测试。
  • 好吧,你为什么不把这个作为答案发布,我会把它作为正确的

标签: python django django-models unique


【解决方案1】:

正如人们在这里所说,它会引发“UNIQUE constraint failed”完整性错误。这可能会发生,因为您没有对唯一性进行任何检查。

我会推荐 David Cramer 的 django-uuidfield。它为您处理所有验证。

https://github.com/dcramer/django-uuidfield

【讨论】:

【解决方案2】:

模型InviteCodes 中的代码字段是唯一字段。如果您尝试使用已经存在的代码创建另一个条目,那么 python 将引发 IntegrityError: UNIQUE constraint failed 异常。

您可以通过从create_invite_code 函数返回一个常量字符串来测试它。例如,

def create_invite_code():
  return 'test'

第一个条目将是唯一的,但在第二个调用中将引发异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多