我该如何在WHERE子句中编写带有子查询的Django查询?

Dav*_*ave 6 python django postgresql subquery python-3.x

我正在使用Django和Python 3.7。我在弄清楚如何编写Django查询(其中有一个子查询作为where子句的一部分)时遇到了麻烦。这是模型...

class Article(models.Model):
    objects = ArticleManager()
    title = models.TextField(default='', null=False)
    created_on = models.DateTimeField(auto_now_add=True)


class ArticleStat(models.Model):
    objects = ArticleStatManager()
    article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlestats')
    elapsed_time_in_seconds = models.IntegerField(default=0, null=False)
    votes = models.FloatField(default=0, null=False)


class StatByHour(models.Model):
    index = models.FloatField(default=0)
    # this tracks the hour when the article came out
    hour_of_day = IntegerField(
        null=False,
        validators=[
            MaxValueValidator(23),
            MinValueValidator(0)
        ]
    )
Run Code Online (Sandbox Code Playgroud)

在PostGres中,查询看起来类似于

SELECT *
FROM article a,
     articlestat ast
WHERE a.id = ast.article_id
  AND ast.votes > 100 * (
    SELECT "index" 
    FROM statbyhour 
    WHERE hour_of_day = extract(hour from (a.created_on + 1000 * interval '1 second')))
Run Code Online (Sandbox Code Playgroud)

注意子查询是WHERE子句的一部分

ast.votes > 100 * (select index from statbyhour where hour_of_day = extract(hour from (a.created_on + 1000 * interval '1 second'))) 
Run Code Online (Sandbox Code Playgroud)

所以我想我可以做这样的事情...

hour_filter = Func(
    Func(
        (F("article__created_on") + avg_fp_time_in_seconds * "interval '1 second'"),
        function='HOUR FROM'),
    function='EXTRACT')
...
votes_criterion2 = Q(votes__gte=F("article__website__stats__total_score") / F(
    "article__website__stats__num_articles") * settings.TRENDING_PCT_FLOOR *
                                StatByHour.objects.get(hour_of_day=hour_filter) * day_of_week_index)
qset = ArticleStat.objects.filter(votes_criterion1 & votes_criterion2,
                                  comments__lte=25)
Run Code Online (Sandbox Code Playgroud)

但这会导致“无法将关键字'article'解析为字段。选项包括:hour_of_day,id,index,num_articles,total_score”错误。我认为这是因为Django在运行其中的较大查询之前就对我的“ StatByHour.objects”查询进行了评估,但是我不知道该如何重写内容才能使子查询同时运行。

编辑: K,将我的子查询移动到实际的“子查询”函数中,并引用了我使用OuterRef创建的过滤器...

hour_filter = Func(
    Func(
        (F("article__created_on") + avg_fp_time_in_seconds * "interval '1 second'"),
        function='HOUR FROM'),
    function='EXTRACT')
query = StatByHour.objects.get(hour_of_day=OuterRef(hour_filter))


...
votes_criterion2 = Q(votes__gte=F("article__website__stats__total_score") / F(
    "article__website__stats__num_articles") * settings.TRENDING_PCT_FLOOR *
                                Subquery(query) * 
                 day_of_week_index)
qset = ArticleStat.objects.filter(votes_criterion1 & votes_criterion2,
                                  comments__lte=25)
Run Code Online (Sandbox Code Playgroud)

结果导致

This queryset contains a reference to an outer query and may only be used in a subquery.
Run Code Online (Sandbox Code Playgroud)

这很奇怪,因为我在子查询中使用它。

编辑#2:即使根据给定的答案更改查询后,也...

hour_filter = Func(
    Func(
        (F("article__created_on") + avg_fp_time_in_seconds * "interval '1 second'"),
        function='HOUR FROM'),
    function='EXTRACT')
query = StatByHour.objects.filter(hour_of_day=OuterRef(hour_filter))[:1]

...
votes_criterion2 = Q(votes__gte=F("article__website__stats__total_score") / F(
    "article__website__stats__num_articles") * settings.TRENDING_PCT_FLOOR *
                                Subquery(query) *
                                day_of_week_index)
qset = ArticleStat.objects.filter(et_criterion1 & et_criterion2 & et_criterion3,
                                  votes_criterion1 & votes_criterion2,
                                  article__front_page_first_appeared_date__isnull=True,
                                  comments__lte=25)
Run Code Online (Sandbox Code Playgroud)

我仍然收到错误

'Func' object has no attribute 'split'
Run Code Online (Sandbox Code Playgroud)

End*_*oth 5

子查询必须是不立即评估的查询,以便可以推迟其评估,直到运行外部查询。get()不符合要求,因为它立即执行并返回一个对象实例而不是Queryset.

但是,替换filter然后get切片[:1]应该可以:

StatByHour.objects.filter(hour_of_day=OuterRef('hour_filter')).values('hour_of_day')[:1]
Run Code Online (Sandbox Code Playgroud)

请注意OuterRef中的字段引用是字符串文字而不是变量。

此外,子查询需要返回单列和单行(因为它们被分配给单个字段),因此values()上面的 和 切片。

另外,我还没有在Q对象中使用子查询;我不确定它会起作用。您可能必须先将子查询输出保存在注释中,然后将其用于过滤器计算。