在Python / Django中生成唯一字符串 [英] Generate a Unique String in Python/Django

查看:124
本文介绍了在Python / Django中生成唯一字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是为我的网站上的用户生成一个大小为5的字符串(密钥)。

What I want is to generate a string(key) of size 5 for my users on my website. More like a BBM PIN.

密钥将包含数字和大写英文字母:

The key will contain numbers and uppercase English letters:


  • AU1B7

  • Y56AX

  • M0K7A

  • AU1B7
  • Y56AX
  • M0K7A

即使我产生了数百万个字符串,我怎么也不能对字符串的唯一性感到满意?

How can I also be at rest about the uniqueness of the strings even if I generate them in millions?

以尽可能多的Python方式,我该怎么做?

In the most pythonic way possible, how can I do this?

推荐答案

我最喜欢的是

import uuid 
uuid.uuid4().hex[:6].upper()

如果使用django,则可以在此字段上设置唯一约束,以确保其唯一。 https://docs.djangoproject。 com / en / dev / ref / models / fields /#django.db.models.Field.unique

If you using django you can set the unique constrain on this field in order to make sure it is unique. https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.unique

这篇关于在Python / Django中生成唯一字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆