Skip to content

Commit

Permalink
refactor load/save functions for JSONField
Browse files Browse the repository at this point in the history
  • Loading branch information
Evert-R committed Nov 28, 2023
1 parent 1f57f40 commit ca456d2
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 14 deletions.
12 changes: 6 additions & 6 deletions backend/result/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ class Meta:

def load_json_data(self):
"""Get json_data as object"""
return json.loads(self.json_data) if self.json_data else {}
return self.json_data if self.json_data else {}

def save_json_data(self, data):
"""Convert json data object to string and merge with json_data, overwriting duplicate keys.
Only valid for JSON objects/Python dicts.
"""Merge data with json_data, overwriting duplicate keys.
"""
updated_data = {**self.load_json_data(), **data}
self.json_data = json.dumps(updated_data)
new_data = self.load_json_data()
new_data.update(data)
self.json_data = new_data
self.save()

def export_admin(self):
"""Export data for admin"""
Expand Down
2 changes: 1 addition & 1 deletion backend/result/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def test_handle_results_with_form(self):
}
handle_results(data, self.session)
assert self.session.result_count() == 2
json_data = json.loads(self.session.result_set.first().json_data)
json_data = self.session.result_set.first().json_data
assert json_data.get('config') != None
assert json_data.get('decision_time') == 42

Expand Down
13 changes: 6 additions & 7 deletions backend/session/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,17 +64,16 @@ def previous_section(self):
return None

def save_json_data(self, data):
"""Convert json data object to string and merge with json_data, overwriting duplicate keys.
Only valid for JSON objects/Python dicts.
"""Merge data with json_data, overwriting duplicate keys.
"""
updated_data = {**self.load_json_data(), **data}
self.json_data = json.dumps(updated_data)
new_data = self.load_json_data()
new_data.update(data)
self.json_data = new_data
self.save()

def load_json_data(self):
"""Get json data object from string json_data"""
return json.loads(self.json_data) if self.json_data else {}
"""Get json data as object"""
return self.json_data if self.json_data else {}

def export_admin(self):
"""Export data for admin"""
Expand Down

0 comments on commit ca456d2

Please sign in to comment.