Skip to content

Commit 27959c8

Browse files
committed
Simplified as_of logic, handle non-id pk fields
1 parent b291f7a commit 27959c8

File tree

1 file changed

+24
-18
lines changed

1 file changed

+24
-18
lines changed

simple_history/manager.py

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -66,22 +66,28 @@ def as_of(self, date):
6666
original model with all the attributes set according to what
6767
was present on the object on the date provided.
6868
"""
69+
if not self.instance:
70+
return self._as_of_set(date)
71+
queryset = self.filter(history_date__lte=date)
72+
try:
73+
history_obj = queryset[0]
74+
except IndexError:
75+
raise self.instance.DoesNotExist(
76+
"%s had not yet been created." %
77+
self.instance._meta.object_name)
78+
if history_obj.history_type == '-':
79+
raise self.instance.DoesNotExist(
80+
"%s had already been deleted." %
81+
self.instance._meta.object_name)
82+
return history_obj.instance
83+
84+
def _as_of_set(self, date):
85+
model = type(self.model().instance) # a bit of a hack to get the model
86+
pk_attr = model._meta.pk.name
6987
queryset = self.filter(history_date__lte=date)
70-
if self.instance:
71-
try:
72-
history_obj = queryset[0]
73-
except IndexError:
74-
raise self.instance.DoesNotExist(
75-
"%s had not yet been created." %
76-
self.instance._meta.object_name)
77-
if history_obj.history_type == '-':
78-
raise self.instance.DoesNotExist(
79-
"%s had already been deleted." %
80-
self.instance._meta.object_name)
81-
return history_obj.instance
82-
historical_ids = set(
83-
queryset.order_by().values_list('id', flat=True))
84-
return (change.instance for change in (
85-
queryset.filter(id=original_pk).latest('history_date')
86-
for original_pk in historical_ids
87-
) if change.history_type != '-')
88+
for original_pk in set(
89+
queryset.order_by().values_list(pk_attr, flat=True)):
90+
last_change = queryset.filter(
91+
**{pk_attr: original_pk}).latest('history_date')
92+
if last_change.history_type != '-':
93+
yield last_change.instance

0 commit comments

Comments
 (0)