Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 948
dandu Avatar asked Apr 18 '09 14:04

dandu


People also ask

How can I get objects in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

How fetch data from many to many field in Django?

A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.


1 Answers

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.

like image 67
João Marcus Avatar answered Sep 25 '22 09:09

João Marcus