前段时间写了一个小巧的用于 django 的 hashids library 。 主要目的是在不改动现有 model fields 的前提下,加入 hashids 支持。
例子:
class TestModel(Model):
hashid = HashidsField(real_field_name="id")
这个 hashid 不会影响原来的 id
field,只是作为一个代理的存在,不会写入数据库,且支持大部分 query,比如:
instance = TestModel.objects.create()
instance2 = TestModel.objects.create()
instance.id # 1
instance2.id # 2
# Allows access to the field
instance.hashid # '1Z'
instance2.hashid # '4x'
# Allows querying by the field
TestModel.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.values
TestModel.objects.values_list("hashid", flat=True) # ["1Z", "4x"]
TestModel.objects.filter(hashid__in=TestModel.objects.values("hashid"))