-
Notifications
You must be signed in to change notification settings - Fork 5
/
ltreefield.py
54 lines (37 loc) · 1.48 KB
/
ltreefield.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from django.db import models
from django.db.models import Lookup
class LtreeField(models.CharField):
description = 'ltree (up to %(max_length)s)'
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 256
super().__init__(*args, **kwargs)
def db_type(self, connection):
return 'ltree'
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
del kwargs['max_length']
return name, path, args, kwargs
class AncestorOrEqual(Lookup):
lookup_name = 'aore'
def as_sql(self, qn, connection):
lhs, lhs_params = self.process_lhs(qn, connection)
rhs, rhs_params = self.process_rhs(qn, connection)
params = lhs_params + rhs_params
return '%s @> %s' % (lhs, rhs), params
LtreeField.register_lookup(AncestorOrEqual)
class DescendantOrEqual(Lookup):
lookup_name = 'dore'
def as_sql(self, qn, connection):
lhs, lhs_params = self.process_lhs(qn, connection)
rhs, rhs_params = self.process_rhs(qn, connection)
params = lhs_params + rhs_params
return '%s <@ %s' % (lhs, rhs), params
LtreeField.register_lookup(DescendantOrEqual)
class Match(Lookup):
lookup_name = 'match'
def as_sql(self, qn, connection):
lhs, lhs_params = self.process_lhs(qn, connection)
rhs, rhs_params = self.process_rhs(qn, connection)
params = lhs_params + rhs_params
return '%s ~ %s' % (lhs, rhs), params
LtreeField.register_lookup(Match)