Skip to content
Advertisement

Update a field of a Django Object

I’m trying to update an object field in django. Usually I would do something like this:

JavaScript

The problem is that the field to modify (in the example above: “name”) is not known and passed as an argument to the post request. So I would have something like this:

JavaScript

now this triggers the error:

JavaScript

What is the correct way to update an “unknown” field of a django object?

UPDATE

Thank you for your answers so far! OK so the way to go is apparently using setattr (as per the answers). Now the problem is that it does not allow me to save the modified object without checking if it is valid.

So I tried using the Serializer to check the object validity but is not working:

JavaScript

error:

JavaScript

Advertisement

Answer

You’re looking for setattr to set an attribute by name.

JavaScript

Of course, this won’t let you automatically attach any arbitrary data to models and expect it to be saved; if you need something like that, maybe use a JSON field.

EDIT:

For using a Django REST Framework serializer (which, cough, wasn’t part of the original question or tags, but could be inferred from query_params), one could do

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement