Is there a way for Django to support composite primary key in combination of select_related or prefetch_related?
I have a Records table with a composite primary key (device_id, created) with a schema like this (simplified):
class Records(models.Model):
class Meta:
managed = False
unique_together = (("device", "created"),)
# The primary key is really (device_id, created)
device = models.ForeignKey("hardware.Device", primary_key=True, on_delete=models.CASCADE)
created = models.DateTimeField(db_index=True)
value = models.FloatField(default=0)
A record belongs to a Device, which is modeled like this (simplified):
class Device(models.Model):
car = models.ForeignKey("cars.Car", on_delete=models.CASCADE)
last_record_at = models.DateTimeField(null=True, blank=True)
I wish to run a query that will return a list of devices, but for each one also contain the last record.
In theory, this would be something like that:
Device.objects.filter(...).select_related("car", "last_record")
But obviously "last_record" is not a foreign key, since Records contains a composite primary key which Django doesn't support.
What would be the best way to do this, other than rewriting the query in raw sql? Is there a reasonable way to override select_related to handle composite keys?