简体   繁体   English

Django order_by ForeignKey设置模型

[英]Django order_by ForeignKey set models

I have following django models 我有以下的Django模型

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)

I need a QuerySet of comments, ordered first by post, then by date. 我需要一个QuerySet注释,首先按帖子排序,然后按日期排序。 But posts must be ordered by its latest comment. 但是帖子必须按其最新评论排序。

If i could use model methods in QuerySet order_by, it would be like this: 如果我可以在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

And the ordering, that i needed, could be: 我需要的排序可能是:

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

But unfortunately, methods in order_by are not allowed. 但不幸的是,不允许使用order_by中的方法。

Please, help. 请帮忙。 Can i have such ordering? 我可以订购吗?

You may not use methods in order_by lookups because they are converted to SQL . 您不能在order_by 查找中使用方法,因为它们已转换为SQL

So, why not convert get_last_comment_date into a field ? 那么,为什么不将get_last_comment_date转换为字段呢? eg using a 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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM