I am using the DRF and I am trying to dynamically select fields from a django model object so that I can compare them to incoming data. I know how to do this manually
def put(self, request):
businessPage = BusinessPage.objects.get(id=request.data['id'])
if businessPage.name != request.data['name']:
businessPage.name = request.data['name']
if businessPage.address != request.data['address']:
businessPage.address = request.data['address']
businessPage.save()
res = {
'status': 'Success'
}
return Response(res)
While this works it feels very messy and repetitive so I started looking for a way to dynamically check if the object field matched the incoming data.
def put(self, request):
businessPage = BusinessPage.objects.get(id=request.data['id'])
for obj in request.data:
if businessPage[obj] != request.data[obj]:
businessPage[obj] = request.data[obj]
businessPage.save()
res = {
'status': 'Success'
}
return Response(res)
I haven't been able to figure out the correct syntax to get the correct field from businessPage. Is this possible? Is there a better way to accomplish this task? Any help here would be much appriciated!