如何查询Django ArrayField的长度? [英] How do I query the length of a Django ArrayField?

查看:242
本文介绍了如何查询Django ArrayField的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模型中有一个ArrayField,我试图注释该字段的长度(到目前为止没有任何运气)

I have an ArrayField in a model, I'm trying to annotate the length of this field ( so far without any luck)

F('field_name__len')不起作用,因为在 F()中不允许加入。甚至
ModelName.objets.values('field_name__len')都不起作用

F('field_name__len') won't work since join is not allowed inside F(). Even ModelName.objets.values('field_name__len') is not working

任何想法吗?

我正在使用 django 1.11

推荐答案

extra()函数已根据文档


使用此不得已的方法

Use this method as a last resort

这是一个旧的API,我们打算在将来的某个时候弃用。仅当无法使用其他查询集方法表达查询时,才使用它。

This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods.

以下是使用自定义注释函数:

Here is how you can do the same thing using a custom Annotation function:

from django.db import models

class ArrayLength(models.Func):
    function = 'CARDINALITY'

MyModel.objects.all().annotate(field_len=ArrayLength('field')).order_by('field_len')

请注意, cardinality() 函数在PostgreSQL 9.4或更高版本中可用后来。如果您使用的是旧版本,则必须使用 array_length()

Note that the cardinality() function is available in PostgreSQL 9.4 or later. If you're using an older version, you have to use array_length():

MyModel.objects.all().annotate(field_len=Func(F('field'), 1, function='array_length')).order_by('field_len')

第二个查询的一个警告是,将在所有非空数组前面排序一个空数组。这可以通过将 NULL 值从 array_length 合并为0来解决。

One caveat with this second query is that an empty array will be sorted in front of all non-empty ones. This could be solved by coalescing NULL values from array_length to 0.

这篇关于如何查询Django ArrayField的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆