Updating Django Models
2010-05-11 05:49:53 | 0 Comment
I'm developing one of my start-ups with Django, the most and widely used Python web framework. Currently I'm not using the form class provided by Django built-in so I'm writing my forms in html. After I have created my update form, I thought updating the posted model info like model.attribute = request.POST['attribute'] is not a good way. I have thought a second and I've found my way.
We are aware of the "get_object_or_404()" method that returns either the model or raises a 404. What this method returns is an instance of this model which means that we are able to use "setattr()" method. So this is what I have came up with:
model = get_object_or_404(Model, id=objectid)
for var in request.POST:
setattr(model, var, request.POST[var])
model.save()
You don't have to do it like this if you are going to update 2 or 3 fields. However if you are going to update around 5+ rows, it's not genius to update them all by hand.
After I wrote this piece of code, I thought "wait a minute, I got many to many relations that comes with the update" and decided to not to operate over that field so I have changed it like this:
model = get_object_or_404(Model, id=objectid)
for var in request.POST:
if var != 'categories':
setattr(model, var, request.POST[var])
# other operations with categories
model.save()
This is all that I have came up with. Hope helps to somebody else. I'd like to hear your thoughts and suggestions.
Check my latest project compector.com where you can post references about your former employers and see what others have said about the future employers. Sign up now and post a reference and share it on twitter or facebook.


Comments
Leave a Response