Changes between Version 2 and Version 4 of Ticket #36352


Ignore:
Timestamp:
Apr 26, 2025, 8:49:49 AM (4 months ago)
Author:
Joseph Yu
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #36352 – Description

    v2 v4  
    11Was upgrading from 4.2.20 to 5.1.8 when tests were failing with a certain query in our app.
    22
    3 Sample code (not actual code and table; only used one table in this case):
     3Models:
    44
    55{{{
    6 >>> a = Tenant.objects.filter(id__in=[1, 3]).values('id').annotate(schema=F('schema_name'), created=F('created_at'))
    7 >>> b = Tenant.objects.filter(id=2).values('id').annotate(schema=F('schema_name'), created=F('created_at'))
    8 >>> c = (a|b).distinct()
    9 >>> d = c.filter(id=OuterRef('id')).values('schema')
    10 >>> e = Tenant.objects.values('schema_name').annotate(created_at=Subquery(d.values('created')))
     6class Foo(models.Model):
     7    name = models.CharField(max_length=255)
     8
     9class Mapping(models.Model):
     10    field = models.CharField(max_length=255)
     11    foo = models.ForeignKey(Foo, null=True, blank=True, on_delete=models.PROTECT)
     12
     13class Tenant(TenantMixin):
     14    created_at = models.DateField(auto_now_add=True)
     15    mapping = models.ForeignKey(Mapping, null=True, blank=True, on_delete=models.PROTECT)
     16}}}
     17
     18Code:
     19
     20{{{
     21a = Mapping.objects.filter(id=1).values('id').annotate(foo=F('foo__name'),foo_id=F('foo_id'))
     22b = Mapping.objects.filter(id=2).values('id').annotate(foo=F('foo__name'),foo_id=F('foo_id'))
     23c = (a|b).distinct()
     24d = c.filter(id=OuterRef('mapping_id')).values('foo')
     25e = Tenant.objects.values('id').annotate(foo_id=Subquery(d.values('foo_id')))
    1126}}}
    1227
     
    2439    ...<2 lines>...
    2540    )
    26 django.core.exceptions.FieldError: Cannot select the 'created' alias. Use annotate() to promote it.
     41django.core.exceptions.FieldError: Cannot select the 'foo_id' alias. Use annotate() to promote it.
    2742}}}
    2843
     
    3045
    3146{{{
    32 >>> d = c.filter(id=OuterRef('id')).values('schema', 'created')
    33 >>> e = Tenant.objects.values('schema_name').annotate(created_at=Subquery(c.values('created')[:1]))
    34 >>> e[:1]
    35 <QuerySet [{'schema_name': 'sample', 'created_at': datetime.date(2024, 11, 4)}]>
     47d = c.filter(id=OuterRef('mapping_id')).values('foo', 'foo_id')
     48e = Tenant.objects.values('id').annotate(foo_id=Subquery(d.values('foo_id')))
    3649}}}
Back to Top