#17522: ModelAdmin.ordering validation too strict -------------------------------------+------------------------------------- Reporter: Sebastian Goll | Owner: nobody Type: Bug | Status: new Component: contrib.admin | Version: dev Severity: Normal | Resolution: Keywords: admin, validation, | Triage Stage: Accepted ordering, strict | Has patch: 1 | Needs documentation: 0 Needs tests: 0 | Patch needs improvement: 1 Easy pickings: 0 | UI/UX: 0 -------------------------------------+-------------------------------------
Comment (by Sylvain Fankhauser): For those like me wondering why the following fails with an error `Cannot resolve keyword 'bar_count' into field` on Django 3.2: {{{ #!python class FooAdmin(admin.ModelAdmin): list_display = ('bar_count',) def get_queryset(self, request): qs = super().get_queryset(request) return qs.annotate( bar_count=models.Count('bar_set') ) def get_ordering(self, request): return ('bar_count',) def bar_count(self, foo): return foo.bar_count bar_count.admin_order_field = 'bar_count' }}} That’s because `super().get_queryset(request)` tries to apply the ordering on the `bar_count` field that’s not yet been added to the queryset. This can be fixed by changing the `get_queryset` method to: {{{ #!python def get_queryset(self, request): qs = self.model._default_manager.get_queryset().annotate( bar_count=models.Count('bar_set') ) ordering = self.get_ordering(request) if ordering: qs = qs.order_by(*ordering) return qs }}} -- Ticket URL: <https://code.djangoproject.com/ticket/17522#comment:10> Django <https://code.djangoproject.com/> The Web framework for perfectionists with deadlines. -- You received this message because you are subscribed to the Google Groups "Django updates" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-updates+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-updates/010701806b7daf6d-d0be33e4-16ef-41eb-a28d-7f2537aacbb7-000000%40eu-central-1.amazonses.com.