如何按 django 中最常用的外键列出

问题描述 投票:0回答:1

我有 2 个模型:发布和评论,如下所示

class Post(models.Model):
id = models.UUIDField( 
     primary_key = True, 
     default = uuid.uuid4, 
     editable = False)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, )
date = models.DateTimeField(default=datetime.now)
title = models.CharField(max_length=100,)
body = models.CharField(max_length=1000)

class Comment(models.Model):
    id = models.UUIDField( 
         primary_key = True, 
         default = uuid.uuid4, 
         editable = False)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, default=None, null=True, blank=True)
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    date = models.DateTimeField(default=datetime.now)
    body = models.CharField(max_length=1000)

我想获得上周评论最多的帖子,那么我如何列出评论最多的帖子。 谢谢!

python-3.x django django-models
1个回答
0
投票

您使用别名并订购:

from datetime import timedelta

from django.db.models import Count
from django.utils.timezone import now

Post.objects.filter(date__gte=now() - timedelta(days=7)).alias(
    n_comments=Count('comment')
).order_by('-c_comments')
© www.soinside.com 2019 - 2024. All rights reserved.