Search code examples
peewee

How do I use the children and tree methods of JSONField?


Let's just say I'm using the sample data used in this blog post. How do I get a list of distinct (or not) tags from all posts using children() or tree()?

I'm thinking I will have to use children, but I'm stumped on how to use it.


Solution

  • These are now documented with examples: children() and tree(). Here is some example code, also from the documentation:

    class KeyData(Model):
        key = TextField()
        data = JSONField()
    
    KeyData.create(key='a', data={'k1': 'v1', 'x1': {'y1': 'z1'}})
    KeyData.create(key='b', data={'x1': {'y1': 'z1', 'y2': 'z2'}})
    
    # We will query the KeyData model for the key and all the
    # keys and values in it's data field, recursively.
    kd = KeyData.data.tree().alias('tree')
    query = (KeyData
             .select(kd.c.key, kd.c.value, kd.c.fullkey)
             .from_(KeyData, kd)
             .order_by(kd.c.key)
             .tuples())
    print(query[:])
    
    # PRINTS:
    [('a',  None,  '{"k1":"v1","x1":{"y1":"z1"}}', '$'),
     ('b',  None,  '{"x1":{"y1":"z1","y2":"z2"}}', '$'),
     ('a',  'k1',  'v1',                           '$.k1'),
     ('a',  'x1',  '{"y1":"z1"}',                  '$.x1'),
     ('b',  'x1',  '{"y1":"z1","y2":"z2"}',        '$.x1'),
     ('a',  'y1',  'z1',                           '$.x1.y1'),
     ('b',  'y1',  'z1',                           '$.x1.y1'),
     ('b',  'y2',  'z2',                           '$.x1.y2')]