Opened 6 years ago

Last modified 5 years ago

#29542 closed Bug

Annotated field created by subquery, referenced inside of F() generates invalid SQL — at Version 1

Reported by: Joey Wilhelm Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Mariusz Felisiak Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Tim Graham)

This seems like it might be related to #29214, but presented itself in a different scenario.

The following code

from django.db import models
from django.db.models import Count, F, IntegerField, OuterRef, Subquery


class Request(models.Model):
    state = models.CharField(max_length=255)


class RequestTask(models.Model):
    request = models.ForeignKey(Request, on_delete=models.CASCADE)
    state = models.CharField(max_length=255)


def find_completed_requests():
        complete = RequestTask.objects.filter(
            request=OuterRef('pk'),
            state='success'
        ).order_by().values('request')
        complete_count = complete.annotate(c=Count('*')).values('c')

        ready_to_complete = Request.objects.annotate(
            total_tasks=Count('tasks'),
            complete_tasks=Subquery(complete_count, output_field=IntegerField())
        ).filter(
            state='in_progress',
            total_tasks=F('complete_tasks')
        )

Generates the error:

Traceback (most recent call last):
  File ".venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: syntax error at or near "SELECT"
LINE 1: ...0."state" = 'success') GROUP BY U0."request_id"), SELECT COU...

This can be resolved by swapping the LHS and RHS of the fields in the final filter, to

complete_tasks=F('total_tasks')

Change History (1)

comment:1 by Tim Graham, 6 years ago

Description: modified (diff)

Do you have a mistake in the ticket? I'm getting FieldError: Cannot resolve keyword 'tasks' into field. Choices are: id, requesttask, state.

Note: See TracTickets for help on using tickets.
Back to Top