Python 在 Django ORM 中查询时如何将字符转换为整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28101580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:44:17  来源:igfitidea点击:

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

pythonmysqldjangoorm

提问by Learner_Programmer

Recently started using Django ORM.I want to execute this query

最近开始使用Django ORM。我想执行这个查询

 select student_id from students where student_id like "%97318%" order by CAST(student_id as UNSIGNED) desc;   

where student_id is a CharField which I want as integer for querying. I tried with

其中 student_id 是一个 CharField,我想要作为查询的整数。我试过

  students.objects.filter(student_id__contains "97318").order('-student_id')

works fine. But don't know and couldn't find how to cast "student_id" to int like the actual MySQL query mentioned above with "Django ORM". should I use raw query or is there a way out? Let me know your suggestions.

工作正常。但是不知道也找不到如何将“student_id”转换为 int 就像上面提到的“Django ORM”的实际 MySQL 查询一样。我应该使用原始查询还是有出路?让我知道你的建议。

采纳答案by erikreed

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

不需要使用的更新替代方法extra是 cast 函数(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

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

回答by catavaran

Use queryset's extra()method:

使用查询集的extra()方法:

students.objects.filter(student_id__contains="97318") \
                .extra({'stident_id_uint': "CAST(student_id as UNSIGNED)"}) \
                .order_by('-student_id_uint')

回答by KinoP

I have tried extra()and annotate()to CAST, but they did not work well with related fields and generates JOINS resulting unexpected queryset sometimes.

我曾尝试extra()annotate()CAST,但他们并没有与相关领域很好地工作,并产生联接有时会造成意想不到的查询集。

What I ended up was to create a Custom Lookup.

我最终是创建一个自定义查找。

The documentation is few but can be found at hereand 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')