Assume that I have the following Django class:
class MyModel(models.Model):
a = models.IntegerField()
created_ts = models.DateTimeField(default=datetime.utcnow, editable=False)
def __str__(self):
return "<%s %s>" % (
self.__class__.__name__,
"; ".join(
[
"ID: %s" % self.pk,
"a: %s" % self.a,
"created_ts: %s" % self.created_ts,
]
)
)
I would like to find the instances of MyModel
with the latest created_ts
for each distinct value of a
. Can I do so with a single QuerySet? If so, what is that QuerySet? If not, what is the most efficient way to get that result?
In the end, I want to have Integer/MyModel-Instance pairs. The answer should look something approximately like this:
{
1: <MyModel ID: 1; a: 1; created_ts: 2004-11-08 06:01:00>,
5: <MyModel ID: 2; a: 5; created_ts: 2004-11-05 08:01:32>,
3: <MyModel ID: 3; a: 3; created_ts: 2004-11-04 11:01:42>,
0: <MyModel ID: 4; a: 0; created_ts: 2004-11-03 06:12:10>,
}