django-hashids:非侵入式的用于 django model 的 hashids library

2020-08-05 07:56:26 +08:00
 ericls

前段时间写了一个小巧的用于 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"))

有兴趣的请看: https://github.com/ericls/django-hashids

1492 次点击
所在节点    分享创造
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/695691

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX