Django annotate with dynamic value
Hi in my model i have property that fully is in cache, not in database
class Model(models.Model):
....
@property
def _get_last_seen_cache_name(self) -> str:
return f'{self.hostname.upper()}_last_seen'
@property
def last_seen(self) -> datetime | None:
cached = cache.get(self._get_last_seen_cache_name, None)
if isinstance(cached, datetime):
return cached
return None
def update_last_seen(self) -> None:
cache.set(self._get_last_seen_cache_name, get_now().replace(microsecond=0), None)
How can i annotate with this value last_seen
queryset. Want use sorting on this column in admin page. But for this, i need get values from cache on annotation, execute cache.get()
with proper key name.
Something like this, not working example:
queryset = super().get_queryset(request)
queryset = queryset.annotate(last_seen=Value(cache.get(Concat('hostname', Value('_last_seen')))), CharField()))
or
queryset = queryset.annotate(last_seen=Value(cache.get(f"{F('hostname')_last_seen}")), CharField()))
I can annotate with literal value, but how annotate with dynamic value, that doesnt exist in database, but in cache or in memory only? How to do hostname substitution in a function?