0

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!

1 Answer 1

1

you can do this:

bp_id = request.data.pop("id")
BusinessPage.objects.filter(id=bp_id).update(**request.data)
Sign up to request clarification or add additional context in comments.

1 Comment

This worked for what I am trying to accomplish. I did have to add a spread operator to get it to work. BusinessPage.objects.filter(id=request.data['id']).update(**request.data)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.