Recently started using Django ORM.I want to execute this query
select student_id from students where student_id like \"%97318%\" order by CAST(student_id a
I have tried extra() and annotate() to CAST, but they did not work well with related fields and generates JOINS resulting unexpected queryset sometimes.
What I ended up was to create a Custom Lookup.
The documentation is few but can be found at here and here
Here is my example:
@Field.register_lookup
class IntegerValue(Transform):
# Register this before you filter things, for example in models.py
lookup_name = 'int' # Used as object.filter(LeftField__int__gte, "777")
bilateral = True # To cast both left and right
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
sql = 'CAST(%s AS UNSIGNED)' % sql
return sql, params
Then below should work:
students.objects.filter(student_id__int__gte="97318").order('-student_id')