gpt4 book ai didi

python - 仅使用数字键查询 JSONField

转载 作者:太空宇宙 更新时间:2023-11-04 05:07:51 26 4
gpt4 key购买 nike

我从 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')

关于python - 仅使用数字键查询 JSONField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43903414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com