簡體   English   中英

Django order_by ForeignKey設置模型

[英]Django order_by ForeignKey set 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)

我需要一個QuerySet注釋,首先按帖子排序,然后按日期排序。 但是帖子必須按其最新評論排序。

如果我可以在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中的方法。

請幫忙。 我可以訂購嗎?

您不能在order_by 查找中使用方法,因為它們已轉換為SQL

那么,為什么不將get_last_comment_date轉換為字段呢? 例如使用信號接收器

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM