Skip to content

Commit

Permalink
Fix patch nested field partial update
Browse files Browse the repository at this point in the history
  • Loading branch information
igieon committed Sep 1, 2021
1 parent 3684d2e commit 934a0f2
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
7 changes: 6 additions & 1 deletion flask_combo_jsonapi/data_layers/alchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,12 @@ def apply_nested_fields(self, data, obj):

nested_fields_to_apply.append({"field": key, "value": nested_objects})
else:
nested_fields_to_apply.append({"field": key, "value": nested_model(**value)})
nested_field = getattr(obj, key)
if nested_field:
for attribute,new_value in value.items():
setattr(nested_field, attribute, new_value)
else:
nested_fields_to_apply.append({"field": key, "value": nested_model(**value)})
elif isinstance(nested_field_inspection.property, ColumnProperty):
nested_fields_to_apply.append({"field": key, "value": value})
else:
Expand Down
38 changes: 38 additions & 0 deletions tests/test_sqlalchemy_data_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,44 @@ def test_patch_detail_nested(client, register_routes, computer, person):
assert response_dict["data"]["attributes"]["single_tag"]["key"] == "new_single_key"


def test_patch_detail_nested_partial_update(client, register_routes, computer, person):
payload = {
"data": {
"id": str(person.person_id),
"type": "person",
"attributes": {
"name": "test2",
"tags": [{"key": "new_key", "value": "new_value"}],
"single_tag": {"key": "new_single_key", "value": "new_single_value"},
},
"relationships": {"computers": {"data": [{"type": "computer", "id": str(computer.id)}]}},
}
}

payload_partial_update = {
"data": {
"id": str(person.person_id),
"type": "person",
"attributes": {
"single_tag": {"value": "new_single_value_partial"},
}
}
}
with client:
response = client.patch(
"/persons/" + str(person.person_id), data=json.dumps(payload), content_type="application/vnd.api+json"
)
assert response.status_code == 200
response = client.patch(
"/persons/" + str(person.person_id), data=json.dumps(payload_partial_update), content_type="application/vnd.api+json"
)
assert response.status_code == 200
response_dict = json.loads(response.get_data())
assert response_dict["data"]["attributes"]["tags"][0]["key"] == "new_key"
assert response_dict["data"]["attributes"]["single_tag"]["key"] == "new_single_key"
assert response_dict["data"]["attributes"]["single_tag"]["value"] == "new_single_value_partial"


def test_delete_detail(client, register_routes, person):
with client:
response = client.delete("/persons/" + str(person.person_id), content_type="application/vnd.api+json")
Expand Down

0 comments on commit 934a0f2

Please sign in to comment.