Sunday, May 27, 2018

How to update Django 2 JSON FIeld?

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

 
 
 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEqej2OF%3D8fWmpQAXNJV10gcNtG7xMDiFVEpArrwMjRp4fVuSA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment