[英]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
字段添加到Author
并last_article_datetime
排序。 更加高效和简洁。 但是,对于任何其他用例,问题仍然存在。
也许是这样的:
Author.objects.annotate(lc=Max('article__created_at')).order_by('lc')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.