'Django bulk update list of objects
I want to create an API endpoint, where you can PUT
list of objects and it will work like this:
- If the ID is specified, query that object and try to update it (if the given ID is not found, show an error)
- If no ID is present for an object, create.
- If any previous objects missing saved to the db missing from this list, delete it from the database.
What I have found and did not work that way (most of them don't work at all):
https://github.com/miki725/django-rest-framework-bulk
https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-update
The example on django-rest site seems to do it like that, however it is not working for me.
I have a serializer:
class InventoryPropertyValuesSerializer(serializers.ModelSerializer):
added_by = serializers.CharField(source='added_by.username', read_only=True)
updated_by = serializers.CharField(source='updated_by.username', read_only=True)
id = serializers.IntegerField(required=False)
class Meta:
model = InventoryPropertyValues
list_serializer_class = CustomBulkListSerializer
fields = '__all__'
ListSerializer
class CustomBulkListSerializer(serializers.ListSerializer):
def update(self, instance, validated_data):
# Maps for id->instance and id->data item.
value_mapping = {value.id: value for value in instance}
data_mapping = {item['id']: item for item in validated_data}
# Perform creations and updates.
ret = []
for value_id, data in data_mapping.items():
value = value_mapping.get(value_id, None)
if value is None:
ret.append(self.child.create(data))
else:
ret.append(self.child.update(value, data))
# Perform deletions.
for value_id, value in value_mapping.items():
if value_id not in data_mapping:
value.delete()
return ret
If I try to run, I get this:
'QuerySet' object has no attribute 'pk'
Solution 1:[1]
It seems that drf-writable-nested does exactly what I want and described in the original post.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kristof Rado |