Meta question

8 views
Skip to first unread message

Mike Dewhirst

unread,
Sep 10, 2019, 4:27:06 AM9/10/19
to Django users
Given a model instance and the name of one of its fields as a string,
how can I get/put a value in that field?

The methods might look like this ...

def get_value(obj, fldname):

    ...

    return value

def put_value(obj, fldname, value):

    pass


Thanks for any hints

Mike


ANi

unread,
Sep 10, 2019, 4:59:08 AM9/10/19
to Django users
getattr(instance, key) to get the value 
setattr(instance, key ,value) to put the value, and remember to do instance.save() otherwise it won't actually be changed.
 
Mike Dewhirst於 2019年9月10日星期二 UTC+8下午4時27分06秒寫道:

Mike Dewhirst

unread,
Sep 11, 2019, 2:27:00 AM9/11/19
to django...@googlegroups.com
Thank you Ani - works nicely :)

Cheers

Mike
> -- You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users...@googlegroups.com
> <mailto:django-users...@googlegroups.com>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/abe0c993-6cf5-4a55-9d3b-9dd213cad8db%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/abe0c993-6cf5-4a55-9d3b-9dd213cad8db%40googlegroups.com?utm_medium=email&utm_source=footer>.

ANi

unread,
Sep 11, 2019, 2:30:00 AM9/11/19
to Django users
:-)  glad to help


Mike Dewhirst於 2019年9月10日星期二 UTC+8下午4時27分06秒寫道:
Reply all
Reply to author
Forward
0 new messages