Skip to main content
 首页 » 编程设计

python之仅使用数字键查询 JSONField

2025年02月15日9sky-heaven

我从 Django 的文档中获取了以下示例,除了替换添加了一个键 '99':

>>> Dog.objects.create(name='Rufus', data={ 
... 'breed': 'labrador', 
...     'owner': { 
...         'name': 'Bob', 
...         'other_pets': [{ 
...             'name': 'Fishy', 
...         }], 
...     }, 
... }) 
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', '99': 'FINDME',}) 
 
>>> Dog.objects.filter(data__breed='collie') 
<QuerySet [<Dog: Meg>]> 

我希望以下内容也返回“Meg”狗:

Dog.objects.filter(data__99='FINDME') 

但是,似乎因为我的 key 是一个整数,Django 没有正确处理这个问题。我如何在 python jsonfields 中拥有作为字符串的整数键?

请您参考如下方法:

有一个wontfix Django ticket关于这个。

是documented behavior :

If the key is an integer, it will be interpreted as an index lookup in an array.

If the key you wish to query by clashes with the name of another lookup, use the jsonfield.contains lookup instead.

所以建议的解决方案是使用 jsonfield.contains :

Dog.objects.filter(data__contains={'99': 'FINDME'}) 

无论如何,我建议你避免在 json 字段中使用数字键,因为使用 contains 方法你无法执行 startswith 和其他类似的查找(参见 similar question ),例如Dog.objects.filter(data__99__startswith='FIND')。