如何编写查询以在django中的json字段中找到值 [英] how to write a query to get find value in a json field in django
问题描述
jsonfield = {'username':'chingo','信誉':'5'}
我如何写一个查询,以便我可以找到一个用户名称存在像
username ='chingo'
query = User.objects.get(jsonfield ['username'] =用户名)
我知道上面的查询是错误的,但我想知道是否有办法访问它?
此用法有些反模式。此外,它的实现不会有正常的性能,并且可能容易出错。
当您需要查找字段时,通常不要使用jsonfield。如Daniel指出的那样,使用RDBMS提供的方式或MongoDB(内部运行在更快的BSON上)。
由于确定性的JSON格式,
你可以通过使用包含
( regex
在处理w / multiple '\'
甚至更慢时出现问题),我认为使用 用户名称
,请使用 名称
:
def make_cond(name,value):
from django.utils import simplejson
cond = simplejson.dumps({name:value})[ 1:-1]#remove'{'and'}'
return''+ cond#avoid'\''
User.objects.get(jsonfield__contains = make_cond价值))
只要
- jsonfield使用相同的转储实用程序(这里的
simplejson
) -
name
和v这个特殊的
不是特别(目前为止我不知道任何egde案例,也许有人可以指出) - 你的jsonfield数据没有被破坏(不太可能)
其实我正在编写一个可编辑的jsonfield,支持此类操作。负面证据如上所述,感觉就像一些黑魔法,好吧。
I have a json field in my database which is like
jsonfield = {'username':'chingo','reputation':'5'}
how can i write a query so that i can find if a user name exists. something like
username = 'chingo'
query = User.objects.get(jsonfield['username']=username)
I know the above query is a wrong but I wanted to know if there is a way to access it?
This usage is somewhat anti-pattern. Also, its implementation is not going to have regular performance, and perhaps is error-prone.
Normally don't use jsonfield when you need to look up through fields. Use the way the RDBMS provides or MongoDB(which internally operates on faster BSON), as Daniel pointed out.
Due to the deterministic of JSON format,
you could achieve it by using contains
(regex
has issue when dealing w/ multiple '\'
and even slower), I don't think it's good to use username
in this way, so use name
instead:
def make_cond(name, value):
from django.utils import simplejson
cond = simplejson.dumps({name:value})[1:-1] # remove '{' and '}'
return ' ' + cond # avoid '\"'
User.objects.get(jsonfield__contains=make_cond(name, value))
It works as long as
- the jsonfield using the same dump utility (the
simplejson
here) name
andvalue
are not too special (I don't know any egde-case so far, maybe someone could point it out)- your jsonfield data is not corrupt (unlikely though)
Actually I'm working on a editable jsonfield and thinking about whether to support such operations. The negative proof is as said above, it feels like some black-magic, well.
这篇关于如何编写查询以在django中的json字段中找到值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!