Django JSONField过滤查询集



对于项目,我使用的是Python 3.6.3,Django 2.0和Postgre 9.4。在我的舱位机票中,有JSONField乘客

    passenger = JSONField(blank=True)

我的乘客 JSON 看起来像这样:

{
    "email": null, 
    "mobile": "21312", 
    "passport": "2141241", 
    "sms_sent": false, 
    "full_name": "something"
},
{
    "email": null, 
    "mobile": null, 
    "passport": "1231231", 
    "sms_sent": false, 
    "full_name": "Irfan"
},
{
    "email": null, 
    "mobile": null, 
    "passport": "1231231", 
    "sms_sent": true, 
    "full_name": "Irfan"
}

现在我有 django 命令,我想在其中过滤具有非空或无的移动票证,并且sms_sent为 False。

    tickets = Ticket.objects.filter(
        date=tomorrow, trip__bus_company=bus_company,
        passenger__sms_sent=False
    ).not_cancelled()

现在 passenger__sms_sent=False 过滤器正在工作,并且正在提供我唯一的 sms_sent=False 的票证。但是passenger__mobile过滤器不起作用。我尝试了所有人:

    tickets = tickets.exclude(passenger__mobile=None)
    tickets = tickets.exclude(passenger__mobile=None).exclude(passenger__mobile='')
    tickets = tickets.exclude(passenger__mobile__isnull=True)
    tickets = tickets.exclude(passenger__exact={'mobile': None})
    tickets = tickets.exclude(passenger__mobile__isnull=True).exclude(passenger__mobile='')
    tickets = tickets.exclude(passenger__mobile__isnull=False).exclude(passenger__mobile='')
    tickets = tickets.exclude(Q(passenger__mobile__isnull=True) | Q(passenger__mobile=''))

并且还将passenger__mobile放入第一个过滤器中,但我无法过滤(排除(passenger__mobile为空的票证,我要么获取所有票证,要么获取空查询集。

现在我可以这样做:

for ticket in tickets:
            if ticket.passenger['mobile'] is not None:
                print(ticket.passenger['mobile'])

但这不是我要找的。我想使用过滤器或排除来获取这些票证。我做错了什么?附言not_cancelled((是我的经理,与乘客领域没有任何关系。

根据这个 https://code.djangoproject.com/ticket/25718(见最后的结束评论(,以下内容应该model.objects.filter(field__key=None)工作(但显然你应该使用带有修复程序的 Django 版本(。

姜戈文档 https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#querying-jsonfield

警告

由于任何字符串都可以是 JSON 对象中的键,因此任何查找其他 下面列出的那些将被解释为密钥查找。没有错误 被提出。格外小心输入错误,并始终检查 您的查询按预期工作。

他们在这里 https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#containment-and-key-operations

最新更新