Django admin custom filter: ProgrammingError: more than one row returned by a subquery used as an expression

795 views
Skip to first unread message

kholidfu

unread,
Mar 22, 2017, 12:25:02 AM3/22/17
to Django users
Hi, I'm trying this custom filter query for django admin

return queryset.extra(select = {'val': "select id from web_quote WHERE character_length(quote_text) < 30"})

and I got something like this:

Programming error: more than one row returned by a subquery used as an expression

Basically I'm trying to filter quote_text column which length of the string less than 30...

Any ideas?

Camilo Torres

unread,
Mar 22, 2017, 11:17:39 AM3/22/17
to Django users
Hi,

The problem with your approach is the SQL will actually be something like this:

select <model fields>,
(select id from web_quote WHERE character_length(quote_text) < 30) as val
from <model table>;

That will fail in RDMS like Postgres if there are more than one "quote_text" with length < 30.

May be you want is something like this:
select <model fields>
from <model table>
where character_length(quote_text) < 30

If that is the case, then you probably will need something like:

return queryset.extra(where=['character_length(quote_text) < 30'])

or even better:
from django.db.models.functions import Length
return quryset.annotate(quote_len=Length('quote_text')).filter(quote_len__lt=30)


Notice extra() is deprecated.
Reply all
Reply to author
Forward
0 new messages