Subquery - Expression | Django 1.11.1

113 views
Skip to first unread message

Алексей Широков

unread,
May 16, 2017, 11:02:37 AM5/16/17
to Django users
Guys help me figure it out.

I use an example from the documentation
https://docs.djangoproject.com/en/1.11/ref/models/expressions/#limiting-a-subquery-to-a-single-column
>>> from datetime import timedelta
>>> from django.utils import timezone
>>> one_day_ago = timezone.now() - timedelta(days=1)
>>> posts = Post.objects.filter(published_at__gte=one_day_ago)
>>> Comment.objects.filter(post__in=Subquery(posts.values('pk')))

But in my case 'pk' is `UUIDField()`
When sql is compiled, `unification_cast_sql()` is called
https://github.com/django/django/blob/stable/1.11.x/django/db/models/expressions.py#L980

The result is the following

ProgrammingError:

SELECT ... FROM table WHERE id in (CAST(SELECT id FROM table2) AS uuid);

Is this a bug or am I doing something wrong???

Thank you.

Simon Charette

unread,
May 16, 2017, 12:30:11 PM5/16/17
to Django users
Hello there,

This is a bug, there's an open Django issue for it [0].

I suggest you don't rely on Subquery for simple pk lookups. Django supported
direct query passing for as long as I can remember.


Cheers,
Simon

Алексей Широков

unread,
May 16, 2017, 1:06:16 PM5/16/17
to Django users
Thanks Simon, I use `OuterRef` when building a queryset so` Subquery` is necessary for me.

For myself, I solved the problem as follows:
...
uuid__in
=Subquery(queryset, output_field=models.IntegerField())
...


Reply all
Reply to author
Forward
0 new messages