I want to Update only name field if only name is sent from frontend, update only image if only image is sent from frontend, update both if name & image is sent from frontend In Django
data =request.data if data['name'] and data['image']: category= Category.objects.get(id=data['id']) category.name=data['name'] category.image=data['image'] category.save() elif data['name']: category= Category.objects.get(id=data['id']) category.name=data['name'] category.save() else: category= Category.objects.get(id=data['id']) category.image=data['image'] category.save()
Advertisement
Answer
You can construct a dictionary that only contains the key-value pairs to update and then use .update(…)
[Django-doc] to update the corresponding Category
record:
categories = Category.objects.filter(id=data['id']) updates = {} if 'name' in data: updates['name'] = data['name'] if 'image' in data: updates['image'] = data['image'] if updates: categories.update(**updates)