dandu
dandu

Reputation: 800

django object get/set field

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.

Upvotes: 28

Views: 35708

Answers (4)

João Marcus
João Marcus

Reputation: 1608

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.

Upvotes: 71

user67416
user67416

Reputation:

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.

Upvotes: 2

StefanNch
StefanNch

Reputation: 2609

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

Upvotes: 3

elzapp
elzapp

Reputation: 1991

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)

Upvotes: 6

Related Questions