Skip to content

Commit 1784e70

Browse files
committed
Add support for renaming annotations
1 parent 08f966c commit 1784e70

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

psqlextra/manager.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,21 @@ def __init__(self, model=None, query=None, using=None, hints=None):
2626
self.conflict_target = None
2727
self.conflict_action = None
2828

29+
def rename_annotations(self, **annotations) -> None:
30+
"""Renames the aliases for the specified annotations:
31+
32+
.annotate(myfield=F('somestuf__myfield'))
33+
.rename_annotations(myfield='field')
34+
35+
Arguments:
36+
annotations:
37+
The annotations to rename. Mapping the
38+
old name to the new name.
39+
"""
40+
41+
self.query.rename_annotations(annotations)
42+
return self
43+
2944
def join(self, **conditions):
3045
"""Adds extra conditions to existing joins.
3146

psqlextra/query.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,30 @@ class ConflictAction(Enum):
1919

2020

2121
class PostgresQuery(sql.Query):
22+
def rename_annotations(self, annotations) -> None:
23+
"""Renames the aliases for the specified annotations:
24+
25+
.annotate(myfield=F('somestuf__myfield'))
26+
.rename_annotations(myfield='field')
27+
28+
Arguments:
29+
annotations:
30+
The annotations to rename. Mapping the
31+
old name to the new name.
32+
"""
33+
34+
for old_name, new_name in annotations.items():
35+
annotation = self.annotations.get(old_name)
36+
37+
if not annotation:
38+
raise SuspiciousOperation((
39+
'Cannot rename annotation "{old_name}" to "{new_name}", because there'
40+
' is no annotation named "{old_name}".'
41+
).format(old_name=old_name, new_name=new_name))
42+
43+
del self.annotations[old_name]
44+
self.annotations[new_name] = annotation
45+
2246
def add_join_conditions(self, conditions: Dict[str, Any]) -> None:
2347
"""Adds an extra condition to an existing JOIN.
2448
@@ -45,7 +69,7 @@ def add_join_conditions(self, conditions: Dict[str, Any]) -> None:
4569
if not join:
4670
raise SuspiciousOperation((
4771
'Cannot add an extra join condition for "%s", there\'s no'
48-
'existing join to add it to.'
72+
' existing join to add it to.'
4973
) % target_table)
5074

5175
# convert the Join object into a ConditionalJoin object, which

0 commit comments

Comments
 (0)