如何使用 Django ORM 编写 MID() 查询

How to write MID() query with Django ORM

我想获得某些列的前 180 个字符,我需要编写具有 MID() or SUBSTRING() 功能的查询,但我没有在 django orm 中找到任何类似的功能。

Django 1.8 有 database functions

Substr 已包括在内。

from django.db.models.functions import Substr
objects = MyModel.objects.annotate(first_180=Substr('fieldname', 1, 180)
for obj in objects:
    print obj.first_180

对于Django中没有的数据库功能,可以自己写function expression