简体   繁体   English

Django模型字段unique = True和default = function

[英]Django model fields unique=True and default=function

So I have a model that looks like this 所以我有一个看起来像这样的模型

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)

What happens if create_invite_code returns a code that already exists in the db, will django call the function again until it finds one that doesn't exist? 如果create_invite_code返回数据库中已经存在的代码会发生什么,django会再次调用该函数,直到找到不存在的代码? Or will it error out? 还是会出错?

The code field in your model InviteCodes is a unique field. 模型InviteCodes的代码字段是唯一字段。 If you tries to create another entry with an already existing code, then python will raise IntegrityError: UNIQUE constraint failed exception. 如果您尝试使用现有代码创建另一个条目,则python将引发IntegrityError: UNIQUE constraint failed异常。

You can test it by returning a constant string from create_invite_code function. 您可以通过从create_invite_code函数返回一个常量字符串来对其进行测试。 For example, 例如,

def create_invite_code():
  return 'test'

The first entry will be unique, but in the second call the exception will be raised. 第一个条目将是唯一的,但是在第二个调用中将引发异常。

As people said here, it will raise "UNIQUE constraint failed" integrity error. 就像人们在这里所说的那样,它将引发“唯一约束失败”完整性错误。 Which could potentially happen cause you're not doing any check for uniqueness. 由于您没有对唯一性进行任何检查,因此有可能发生这种情况。

I would recommend django-uuidfield by David Cramer. 我会推荐David Cramer的django-uuidfield。 It handles all the validation for you. 它为您处理所有验证。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM