postgresql - Query the contents of a Django model's JSONField -
i'm trying figure out way query data inside postgres jsonfield on particular instance of model.
from i've seen, use cases things equivalent of if had attributes jsonfield, , selecting instances of model attributes ->> color = 'red' or whatever.
so let's give more real example, let's have model shoe
, has price , quantity , whatever fields, jsonfield called versions
, array of objects, each objects having things make each version special.
so if 1 instance of shoe model air jordans, attributes jsonfield like:
[ { color: black, edition: limited, tonguecolor: red }, { color: black, edition: standard }, { color: gold, edition: fancy, bright: } ]
so there's 2 things can do, can:
- query model shoes have available version color: black (which return our air jordans, plus maybe other shoes), or
- query instance of model objects inside jsonfield versions color = black. if had
shoe.objects.filter(name='air jordans')
or something, tack on method or @ end return first 2 objects abovecolor == black
?
i can find examples online of doing first, not second.
i bring object memory , filter there, jsonfield hoping store large quantities of arbitrary data, , being able query without bringing whole blob memory important. can jsonfield support this?
@antoinepinsard pointed me in right direction - json_to_recordset().
i'm using like:
select * ( select j.* shoes, json_to_recordset(json_field_name) j(color text, edition text, tonguecolor: text, bright text) shoes.shoe_name = 'air jordan' ) subset subset.color= "black"
so inner select statement build internally recordset looks this:
color | edition | tonguecolor | bright ------+----------+-------------+-------- black | limited | red | black | standard | | gold | fancy | |
and outer statement query internal recordset (in case, color = 'black' , return:
color | edition | tonguecolor | bright ------+----------+-------------+-------- black | limited | red | black | standard | |
thanks everyone!
Comments
Post a Comment