So, I have these models:
class Computer(models.Model):
hostname = models.CharField(primary_key=True, max_length=6)
<other computer info fields>
class ComputerRecord(models.Model):
id = models.AutoField(primary_key=True)
pc = models.ForeignKey(Computer, on_delete=models.CASCADE)
ts = models.DateTimeField(blank=False)
<other computerrecord info fields>
I want to get the row / computerrecord instance that has the max ts for each pc (Computer model)
In sql would be something like this:
SELECT hub_computerrecord.*
FROM hub_computerrecord
JOIN (
SELECT pc_id, MAX(ts) AS max_ts
FROM hub_computerrecord
GROUP BY pc_id
) AS maxs ON hub_computerrecord.pc_id = maxs.pc_id
WHERE hub_computerrecord.ts = maxs.max_ts;
Note (edit): There are lot of ComputerRecord instances (10000+) so anything too inefficient won't work