How to update Django 2 JSON FIeld?

7 views
Skip to first unread message

Mark Phillips

unread,
May 27, 2018, 3:46:47 PM5/27/18
to django users
I have a model called Document with a field called metadata defined as JSONField(blank=True). I want to be able to search the Document model for a certain key in the metadata field, and change that key.

For example, there is a key 'People' in some of the Document objects, and I want to change that key to "Person". I tried these queries - 

>>> fred=Document.objects.filter(metadata__has_key='People')
>>> fred
<QuerySet [<Document: a new title 2>, <Document: adfadfasdf>, <Document: asdfasdf>, <Document: gggggg>, <Document: hsfdgsdf>, <Document: the title>]>
>>> sam = fred[0].metadata
>>> sam
{'Date': '05/07/1994', 'Title': 'title 2', 'Location': 'Tempe', 'Orientation': 'Landscape', 'Photo Type': 'Individual', 'URL': 'http://sam.com', 'People': ['Tina Phillips Roderique'], 'Decade': '1990', 'a boolean': False}
>>> sam['Person'] = sam.pop('People')
>>> sam
{'Date': '05/07/1994', 'Title': 'title 2', 'Location': 'Tempe', 'Orientation': 'Landscape', 'Photo Type': 'Individual', 'Person': ['Tina Phillips Roderique'], 'URL': 'http://sam.com', 'Decade': '1990', 'a boolean': False}
>>> fred[0].metadata = sam
>>> fred[0].metadata
{'Date': '05/07/1994', 'Title': 'title 2', 'Location': 'Tempe', 'Orientation': 'Landscape', 'Photo Type': 'Individual', 'URL': 'http://sam.com', 'People': ['Tina Phillips Roderique'], 'Decade': '1990', 'a boolean': False}
>>> 

I was able to change the key in the dictionary 'sam', but when I tried to replace the metadata dictionary in fred[0], it did not update. I must be missing something in how to update a field in a django model.

Thanks for any suggestions you may have!

Mark

 
 
 

Reply all
Reply to author
Forward
0 new messages