Suppose I want to show a list of runners ordered by their last sprint date.
class Runner(models.Model): name = models.CharField(max_length=255) class Sprint(models.Model): runner = models.ForeignKey(Runner) time = models.PositiveIntegerField() created = models.DateTimeField(auto_now_add=True)
This is a quick sketch of what I will do in SQL:
SELECT runner.id, runner.name, sprint.time FROM runner LEFT JOIN sprint ON (sprint.runner_id = runner.id) WHERE sprint.id = ( SELECT sprint_inner.id FROM sprint as sprint_inner WHERE sprint_inner.runner_id = runner.id ORDER BY sprint_inner.created DESC LIMIT 1 ) OR sprint.id = NULL ORDER BY sprint.time ASC
The Django QuerySet documentation says:
It is allowed to set a multivalued field for organizing the results (for example, the ManyToManyField field). Usually this will not be a reasonable thing and its truly advanced use function. However, if you know that your filtering requests or available data implies that there will be only one custom piece of data for each of the main elements that you select, the order may be exactly what you want to do. Use multiple-field ordering with caution and make sure the results are expected.
I think I need to apply some filter here, but I'm not sure what exactly Django expects ...
One note, as this is not obvious in this example: the Runner table will contain several hundred records, sprints will also have several hundred, and on some subsequent days, probably several thousand records. The data will be displayed paginated, so sorting in Python is not an option.
The only other opportunity I see is to write SQL myself, but I would like to avoid this at all costs.
Streerer
source share