﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
29396	The __year lookp crashes with IndexError when passed a non-direct values/expression.	Dmitry Shachnev	Windson yang	"With the following models:
{{{
#!python
class ModelWithDate(models.Model):
    id = models.AutoField(primary_key=True)
    date = models.DateField()

class ModelWithYear(models.Model):
    id = models.AutoField(primary_key=True)
    year = models.IntegerField()
    date_ref = models.ForeignKey(to=ModelWithDate, on_delete=models.CASCADE)
}}}

the following code:
{{{
#!python
>>> dates = ModelWithDate.objects.filter(date__year__gte=OuterRef(""year""))
>>> dates_subq = Subquery(dates.values(""id""))
>>> ModelWithYear.objects.filter(date_ref__in=dates_subq)
}}}

causes an exception:
{{{
#!pytb
Traceback (most recent call last):
  ...
  File ""/usr/lib/python3/dist-packages/django/db/models/lookups.py"", line 90, in process_rhs
    sql, params = compiler.compile(value)
  File ""/usr/lib/python3/dist-packages/django/db/models/sql/compiler.py"", line 391, in compile
    sql, params = node.as_sql(self, self.connection)
  File ""/usr/lib/python3/dist-packages/django/db/models/expressions.py"", line 1041, in as_sql
    template_params['subquery'], sql_params = self.queryset.query.get_compiler(connection=connection).as_sql()
  File ""/usr/lib/python3/dist-packages/django/db/models/sql/compiler.py"", line 459, in as_sql
    where, w_params = self.compile(self.where) if self.where is not None else ("""", [])
  File ""/usr/lib/python3/dist-packages/django/db/models/sql/compiler.py"", line 391, in compile
    sql, params = node.as_sql(self, self.connection)
  File ""/usr/lib/python3/dist-packages/django/db/models/sql/where.py"", line 80, in as_sql
    sql, params = compiler.compile(child)
  File ""/usr/lib/python3/dist-packages/django/db/models/sql/compiler.py"", line 391, in compile
    sql, params = node.as_sql(self, self.connection)
  File ""/usr/lib/python3/dist-packages/django/db/models/lookups.py"", line 523, in as_sql
    start, finish = self.year_lookup_bounds(connection, rhs_params[0])
IndexError: list index out of range
}}}

The same happens if I create an annotation using ExtractYear and use it directly.

A small test project is attached. The bug can be reproduced with “DJANGO_SETTINGS_MODULE=settings python3 ./test.py”. Tested with Django 2.0.5 and 1.11.13."	Bug	closed	Database layer (models, ORM)	dev	Normal	fixed			Accepted	1	0	0	1	0	0
