Mihail Panayotov
Mihail Panayotov

Reputation: 320

Use TO_CHAR in Django filter query method that makes a join

I need to cast a field via TO_CHAR using Django. I know I can:

Author.objects.extra(where=["TO_CHAR(name) = 'John'"])

and I also can:

Author.objects.filter(article__name='CoolArticle')

which will make the join on Article behind the scenes. Is there a way to combine both and achieve this:

author.articles.filter(website__name='AwesomeWeb')
# where website__name is casted via TO_CHAR

Upvotes: 1

Views: 1151

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599620

You need to write a custom transformer lookup. Something like:

from django.db.models import Transform
from django.db.models.fields import Field

class ToChar(Transform):
    lookup_name = 'tochar'
    function = 'TO_CHAR'

Field.register_lookup(ToChar)

Now you should be able to do:

author.articles.filter(website__name__tochar='AwesomeWeb')

Upvotes: 2

Related Questions