2👍
Just add field ‘last_post_datetime’ in Thread and update this field in Post.save:
class Thread(models.Model)
...
last_post_datetime = models.DateTimeField(blank=True,null=True)
class Post(Meta):
...
def save(self):
super(Post, self).save()
self.thread.last_post_datetime = max(self.thread.last_post_datetime, self.createtime)
self.thread.save()
and use simple query
Thread.objects.order_by('-createtime')[:10]
And of course I recommend you to add index on this field:
ALTER TABLE <post> ADD INDEX createtime (createtime);
1👍
There is probably an easier way 🙂 Add a DateTimeField to the Post object with a “date_posted” field or something like that. Then do this:
Thread.objects.order_by('-post_set__date_posted')[:10]
This is basically a variant on the answer of Glader, but I like this better because it doesn’t require a custom save()
method if you set the auto_now_add
to True on the DateTimeField. I prefer to keep the logic of a model as much inside the model itself as possible.
- [Django]-Django admin to edit foreign keys inline
- [Django]-Override Meta in ModelForm
- [Django]-Conditional nested filters in Django
- [Django]-AttributeError: 'CharField' object has no attribute 'model'
Source:stackexchange.com