views:

93

answers:

1

Hallo people,

I have two Models, Thread and Post, where one Thread can have many Posts. I want to retrieve the active threads by sorting by 'post_set.createtime'. In the end, I want to get exactly ten Threads that had the most recent activity. Is this possible using no own SQL?

Thanks a lot in advance.

[Copying the model definitions from the OP's reply to the body of the question.]

class Topic(models.Model):
    title = models.CharField(max_length=50)
    order = models.SmallIntegerField() #used for visual stuff

class Thread(models.Model):
    topic = models.ForeignKey(Topic)
    name = models.CharField(max_length=50)

class Post(Meta):
    thread = models.ForeignKey(Thread)
    text = models.TextField()

class Meta(models.Model):
    createuser = models.ForeignKey(User,default=None,blank=True,null=True,related_name="createuser")
    createtime = models.DateTimeField(default=datetime.datetime.now,blank=True,null=True)
    edituser = models.ForeignKey(User,default=None,null=True,related_name="edituser",blank=True)
    edittime = models.DateTimeField(default=None,null=True,blank=True)
+2  A: 

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);
Glader