Django:如何有条件地过滤外键

时间:2019-05-13 19:09:23

标签: django django-queryset

假设我有一些如下的类:

from django.db import models

REVIEW_RATING_CHOICES = (
    (5, 'Five'),
    (4, 'Four'),
    (3, 'Three'),
    (2, 'Two'),
    (1, 'One'),
)

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

class Article(models.Model):
    publication = models.ForeignKey(Publication)
    content = models.TextField()

class Review(models.Model):
    date = models.DateTimeField()
    article = models.ForeignKey(Article)
    rating = models.IntegerField(choices=REVIEW_RATING_CHOICES)

假设我们要突出显示“非常好”的出版物,我们将它们定义为可以立即对任何文章进行五星级评价的出版物。

我怎样才能获得对某篇文章的“ 第一”(即“ Review.date”最早的价值”)中的“ 任何”评论给予5星评价的出版物? >

1 个答案:

答案 0 :(得分:0)

我相信您可以嵌套子查询,但是我担心它的性能。

from django.db.models import OuterRef, Subquery, Exists

earliest_review = Review.objects.filter(article_id=OuterRef('id')).order_by('date')
initially_approved_articles = Article.objects.annotate(
    earliest_review_status=Subquery(earliest_review.values('status')[:1]),
).filter(
    earliest_review_status=APPROVED,
    publication_id=OuterRef('id'),
)
Publication.objects.annotate(
    has_initially_approved_article=Exists(initially_approved_articles),
).filter(
    has_initially_approved_article=True,
)