W1ldPo1nter / django-queryable-properties

Write Django model properties that can be used in database queries.
BSD 3-Clause "New" or "Revised" License
71 stars 1 forks source link

Issue with sorting in django-admin #7

Closed Elendiar closed 1 year ago

Elendiar commented 1 year ago

Hi, in my Model i have a property, that exists in cache only. In admin i also show this property, but how i can sort by this property. if its for each model different and string like 2023-02-07 10:03:44. Its sortable with annotation only, but with annotation i get exception: queryable_properties.exceptions.QueryablePropertyError: Queryable property "app.models.Model.last_seen" has a circular dependency and requires itself. Is it possible release sorting in admin with fully "virtual" property, which is not related to database? _(django docs says that: Usually, elements of listdisplay that aren’t actual database fields can’t be used in sorting (because Django does all the sorting at the database level).) I thought that with django-queryable-properties I can make it.

class Model(models.Model):

    ....

    @queryable_property(cached=True)
        def last_seen(self) -> str:
        return str(cache.get(self._get_last_seen_cache_name, "-"))

    def update_last_seen(self) -> None:
        cache.set(self._get_last_seen_cache_name, get_now().replace(microsecond=0), None)
W1ldPo1nter commented 1 year ago

Is it possible release sorting in admin with fully "virtual" property, which is not related to database?

No. It's just as stated in the Django docs: ordering in the admin is performed at the database level, which means that you need a model field or an annotation to order by. That's why queryable properties can only be used for ordering in the admin if they are annotatable - because they have a database representation in this case.

The property in your example code shouldn't really be a queryable property anyway, precisely because there is no database interaction/representation and the entire point of queryable properties is to implement properties that can be used on the object level and in queryset/database operations. Your property could therefore simply be a cached_property, but you won't be able to use it for sorting in the admin without reimplementing how the admin sorts yourself either way.

Elendiar commented 1 year ago

@W1ldPo1nter Thanks for the detailed answer.