2012-03-01 93 views
0

我有以下Django模型Django的ORDER_BY ForeignKey的集模型

class Post(models.Model): 
    title = models.CharField(max_length=240) 

class Comment(models.Model): 
    post = models.ForeignKey(Post) 
    date = models.DateTimeField(auto_now_add=True) 

我需要评论一个QuerySet,首先下令后,然后按日期。 但帖子必须按其最新评论排序。

,如果我能在查询集ORDER_BY使用模型的方法,这将是这样的:

class Post(models.Model): 
    title = models.CharField(max_length=240) 

    def get_last_comment_date(self): 
     return self.comment_set.order_by('-date')[0].date 

而且顺序,我需要的,可能是:

Comment.objects.all().order_by('post__get_last_comment_date', '-date') 

但不幸的是,在方法order_by是不允许的。

请帮忙。我可以有这样的订购吗?

回答

4

您可能不会使用order_by lookups中的方法,因为它们已转换为SQL

那么,为什么不将get_last_comment_date转换为字段?例如使用signal receiver

from django.db.models import signals 

class Post(models.Model): 
    title = models.CharField(max_length=240) 
    last_comment_date = models.DateField(null=True, blank=True) 

def post_last_comment_date(sender, instance=None, **kwargs): 
    try: 
     last_comment_date = self.comment_set.order_by('-date')[0].date 
    except Comment.DoesNotExist: 
     return 

    if last_comment_date != comment.post.last_comment_date: 
     comment.post.last_comment_date = last_comment_date 
     comment.post.save() 

signals.post_save.connect(post_last_comment_date, sender=Comment) 

现在,您可以:Comment.objects.order_by('post__last_comment_date', '-date')

+0

谢谢!我担心,我将不得不向last post添加'last_comment_date'字段,并在每次发生针对特定帖子的新评论时更新它。但是你的解决方案要好得多! – stalk 2012-03-01 11:46:31

+0

糟糕,看起来我以前的评论太快了。此解决方案将更新每个新评论的字段。它的工作原理(修改了一些代码,即将'self'重命名为'instance'),但它是否会增加每个新评论数据库的额外负载? – stalk 2012-03-01 12:32:34

+0

是的,我们在发布评论时发生2次(边缘案例中的3次)查询,而在显示评论时发生了许多查询。对我来说听起来很公平。 – jpic 2012-03-01 12:36:43

相关问题