繁体   English   中英

django:在模型管理器中按foreignkey排序

[英]django: sort by foreignkey in model manager

class Author(models.Model):
    name = models.CharField()

class Article(models.Model):
    author = models.ForeignKey(Author)
    created_at = models.DateTimeField(auto_now_add=True)

Author的自定义模型管理器中,如何按作者最新Article的创建日期对所有作者进行排序? 不使用原始sql或for循环是否可能?

为了显示研究成果并阐明问题,这是我在原始Python中如何执行此操作的(伪)代码。 它未经测试,可能由于if not article.author in sorted_authors条件中if not article.author in sorted_authors

from django.db import models
from .models import Article

class AuthorsManager(models.Manager):
    def get_sorted_authors(self):

        articles = Article.objects.all().order_by('creation_date')

        sorted_authors = []
        for article in articles:
            # not sure if this if condition would work
            if not article.author in sorted_authors:
                sorted_authors.append(article.author)

        return sorted_authors

另一个可能的解决方案:将last_article_datetime字段添加到Authorlast_article_datetime排序。 更加高效和简洁。 但是,对于任何其他用例,问题仍然存在。

也许是这样的:

Author.objects.annotate(lc=Max('article__created_at')).order_by('lc')

暂无
暂无

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

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