非侵入式hashids库Django
django-hashids的Python项目详细描述
Django哈希ID
django hashids是django的一个简单的、非侵入性的hashids库。它充当一个模型字段,但它不接触数据库或更改模型。在
安装
pip install django-hashids
django-hashids
是用django1.11、2.2、3.0、3.1和python3.6、3.7、3.8、3.9测试的。在
使用
向任何模型添加HashidsField
TestModel.hashid
字段将代理TestModel.id
字段,但所有查询都将返回并接收哈希ID字符串。TestModel.id
将像以前一样工作。在
示例
instance=TestModel.objects.create()instance2=TestModel.objects.create()instance.id# 1instance2.id# 2# Allows access to the fieldinstance.hashid# '1Z'instance2.hashid# '4x'# Allows querying by the fieldTestModel.objects.get(hashid="1Z")TestModel.objects.filter(hashid="1Z")TestModel.objects.filter(hashid__in=["1Z","4x"])TestModel.objects.filter(hashid__gt="1Z")# same as id__gt=1, would return instance 2# Allows usage in queryset.valuesTestModel.objects.values_list("hashid",flat=True)# ["1Z", "4x"]TestModel.objects.filter(hashid__in=TestModel.objects.values("hashid"))
配置
可以在设置文件中添加以下属性来设置HashidsField
的默认参数:
DJANGO_HASHIDS_SALT
:默认saltDJANGO_HASHIDS_MIN_LENGTH
:默认最小长度DJANGO_HASHIDS_ALPHABET
:默认字母表
HashidsField
不需要任何参数,但可以提供以下参数来修改其行为。在
Name | Description |
---|---|
^{ | The proxied field name |
^{ | The hashids instance used to encode/decode for this field |
^{ | The salt used for this field to generate hashids |
^{ | The minimum length of hashids generated for this field |
^{ | The alphabet used by this field to generate hashids |
参数hashids_instance
与salt
、min_length
和{
还支持一些常见的模型参数,如verbose_name
。在
- 项目
标签: