如何使用Django将uuid过滤为文本?

时间:2019-04-04 01:54:36

标签: python django

如何使用Django将uuid过滤为文本?
例如,我想做下面的事情。

class Group(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
Group.objects.filter(id__startswith='000')

在这种情况下,我收到了django.core.exceptions.FieldError: Related Field got invalid lookup: startswith

我需要额外使用吗?

2 个答案:

答案 0 :(得分:0)

正如我在评论中说的,I'm not sure if UUIDFields are searchable(至少不是您想要的确切方式)。一种替代方法(尽管可能不是最有效的)是在模型中包含一个包含UUID字符串表示形式的属性或annotated field

答案 1 :(得分:0)

class Cast(Func):
    function = "CAST"
    template = "%(function)s(%(expressions)s AS varchar)"

Group.objects.annotate(sid=Cast(id)).filter(sid__startswith='000')

Meybe那是什么?