V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
ericls
V2EX  ›  分享创造

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

  •  1
     
  •   ericls ·
    ericls · 2020-08-05 07:56:26 +08:00 · 1475 次点击
    这是一个创建于 1332 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4132 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 01:00 · PVG 09:00 · LAX 18:00 · JFK 21:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.