我需要使用Django通过TO_CHAR投射字段。我知道我可以做到:
Author.objects.extra(where=["TO_CHAR(name) = 'John'"])
我也可以:
Author.objects.filter(article__name='CoolArticle')
将在幕后加入Article。有没有办法将两者结合起来并实现这一目标:
author.articles.filter(website__name='AwesomeWeb')
# where website__name is casted via TO_CHAR
答案 0 :(得分:1)
您需要写一个custom transformer lookup。像这样:
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)
现在您应该能够做到:
author.articles.filter(website__name__tochar='AwesomeWeb')