How do i cast char to integer while querying in django ORM?

后端 未结 3 1771
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 11:03

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         


        
相关标签:
3条回答
  • 2020-11-28 11:18

    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')
    
    0 讨论(0)
  • 2020-11-28 11:19

    An updated alternative without requiring the use of extra is the cast function (new in Django 1.10):

    >>> from django.db.models import FloatField
    >>> from django.db.models.functions import Cast
    >>> Value.objects.create(integer=4)
    >>> value = Value.objects.annotate(as_float=Cast('integer', FloatField())).get()> 
    >>> print(value.as_float)
    4.0
    

    From https://docs.djangoproject.com/en/1.10/ref/models/database-functions/#cast

    0 讨论(0)
  • 2020-11-28 11:22

    Use queryset's extra() method:

    students.objects.filter(student_id__contains="97318") \
                    .extra({'stident_id_uint': "CAST(student_id as UNSIGNED)"}) \
                    .order_by('-student_id_uint')
    
    0 讨论(0)
提交回复
热议问题