views:

1324

answers:

2

Can I get the value of an object field some other way than "obj.field". Does something like "obj.get('field')" exist? Same thing for setting the value of the field.

+1  A: 

why do you want this?

You could use

obj.__dict__['field']

i guess... though it's not a method call

changed=[field for (field,value) in newObj.__dict__ if oldObj.__dict__[field] != value]

will give you a list of all the fields that where changed.

(though I'm not 100% sure)

elzapp
after submitting an edit form for that object I have:oldObj = ObjModel.objects.get(pk=pk)newObj = editForm.save(commit = False)and I want to compare the two objects, I need to know which fields were changed by the edit form. Is there any way easier way of doing that, except comparing the objects field by field?
dandu
+7  A: 

To get the value of a field:

getattr(obj, 'field_name')

To set the value of a field:

setattr(obj, 'field_name', 'field value')

To get all the fields and values for a Django object:

[(field.name, getattr(obj,field.name)) for field in obj._meta.fields]
João Marcus
or, to update '''obj''' with items from a dictionary: [setattr(obj, key, value) for (key, value) in dictionary.items()]
mariotomo