Vitalii Korniichuk
Vitalii Korniichuk

Reputation: 33

How to set date_hierarchy to an annotation field

I have a Model and its Manager. I created an annotated field date (which returns not null date from start or set date).

class TimerManager(models.Manager):
    def get_queryset(self):
        return (
            super()
            .get_queryset()
            .annotate(
                date=models.ExpressionWrapper(
                    functions.Coalesce(
                        models.F("start__date"),
                        models.F("actual_date"),
                    ),
                    output_field=models.DateField(
                        _("date"),
                    ),
                ),
            )
        )


class Timer(models.Model):
    start = models.DateTimeField(_("start"), auto_now_add=True)
    end = models.DateTimeField(_("end"), null=True, blank=True)
    set_date = models.DateField(_("set date"), null=True, blank=True)

    objects = TimerManager()

I want to use this annotated field in date_hierarchy of Timer's ModelAdmin but this error occurres:

<class 'timers.admin.TimerAdmin'>: (admin.E127) The value of 'date_hierarchy' refers to 'date', which does not refer to a Field.

list_display can show annotated fields by reffering ModelAdmin's methods which explicitly return these properties:

@admin.register(Timer)
class TimerAdmin(admin.ModelAdmin):
    list_display = ["pk", "start", "end", "date"]
    exclude = []

    def date(self, obj):
        return obj.date

We use this method in date_hierarchy: date_hierarchy = "date". But the issue still happens.

Upvotes: 1

Views: 117

Answers (0)

Related Questions