I'm writing a Django app that performs various functions, including inserting, or updating new records into the database via the URL.
So some internal application sends off a request to /import/?a=1&b=2&c=3
, for example.
In the view, I want to create a new object, foo = Foo()
and have the members of foo
set to the data in the request.GET dictionary.
Here is what I'm doing now:
/import/?a=1&b=2&c=3
foo = Foo()
Here is what I got thus far:
foo.a = request['a']
foo.b = request['b']
foo.c = request['c']
Obviously this is tedious and error prone. The data in the URL has the exact same name as the object's members so it is a simple 1-to-1 mapping.
Ideally, I would like to do able to do something like this:
foo = Foo()
foo.update(request.GET)
or something to that effect.
Thanks!
Python Dictionary update() Method Python update() method updates the dictionary with the key and value pairs. It inserts key/value if it is not present. It updates key/value if it is already present in the dictionary. It also allows an iterable of key/value pairs to update the dictionary.
Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.
Modifying a value in a dictionary is pretty similar to modifying an element in a list. You give the name of the dictionary and then the key in square brackets, and set that equal to the new value.
You can use the setattr function to dynamically set attributes:
for key,value in request.GET.items():
setattr(foo, key, value)
If request.GET
is a dictionary and class Foo
does not use __slots__
, then this should also work:
# foo is a Foo instance
foo.__dict__.update(request.GET)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With