Add ordering mixin for class based generic views
|Reported by:||Aymeric Augustin||Owned by:||pjrharley|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Currently, if the model used by by a date-based generic view doesn't have an
ordering and pagination is enabled, results will be random. Defining an
ordering on the model isn't totally satisfying because it has global effects, and it adds an overhead to every query involving the model.
Another workaround is to define
queryset = MyModel.objects.order_by('-<date_field>') in every view. But CBVs are precisely about removing as much boilerplate as possible.
So here's a draft of an API for ordering:
class BaseDateListView(...): ordering = None def get_ordering(self): return self.get_date_field() if self.ordering is None else self.ordering def get_dated_queryset(self, **lookups): ... if not qs.ordered(): qs = qs.order_by(self.get_ordering()) ...
self.get_ordering() could return
'-<date_field>' for the archive view for backwards compatibility.
This would be a better fix for #18354.
Change History (12)
comment:3 Changed 4 years ago by
|Summary:||Date-based generic views should enforce ordering → Add ordering mixin for class based generic views|