28

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.

MackM
  • 2,906
  • 5
  • 31
  • 45
dandu
  • 800
  • 1
  • 8
  • 18
  • possible duplicate of [How to introspect django model fields?](http://stackoverflow.com/questions/2384436/how-to-introspect-django-model-fields) – Anurag Uniyal Sep 02 '11 at 18:25

4 Answers4

71

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]

You can read the documentation of Model _meta API which is really useful.

Mohammed Shareef C
  • 3,829
  • 25
  • 35
João Marcus
  • 1,610
  • 1
  • 13
  • 20
  • 2
    or, to update '''obj''' with items from a dictionary: [setattr(obj, key, value) for (key, value) in dictionary.items()] – mariotomo Aug 19 '09 at 12:15
6

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
  • 1,961
  • 4
  • 15
  • 22
  • 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 Apr 18 '09 at 15:26
  • Doesn't always work (foreign keys break this). Use @João Marcus answer instead. – pseudosudo May 13 '14 at 19:57
3

If somebody stumbles upon this little question, the answer is right here: How to introspect django model fields?

Community
  • 1
  • 1
StefanNch
  • 2,569
  • 24
  • 31
2

To get related fields:

def getattr_related(obj, fields):
    a = getattr(obj, fields.pop(0))
    if not len(fields): return a
    else:               return getattr_related(a, fields)

E.g.,

getattr_related(a, "some__field".split("__"))

Dunno, perhaps there's a better way to do it but that worked for me.