109π
β
Use value_from_object
:
field_name = 'name'
obj = MyModel.objects.first()
field_object = MyModel._meta.get_field(field_name)
field_value = field_object.value_from_object(obj)
Which is the same as getattr
:
field_name = 'name'
obj = MyModel.objects.first()
field_object = MyModel._meta.get_field(field_name)
field_value = getattr(obj, field_object.attname)
Or if you know the field name and just want to get value using field name, you do not need to retrieve field object firstly:
field_name = 'name'
obj = MyModel.objects.first()
field_value = getattr(obj, field_name)
π€awesoon
16π
Assuming you have a model as,
class SampleModel(models.Model):
name = models.CharField(max_length=120)
Then you will get the value of name
field of model instance by,
sample_instance = SampleModel.objects.get(id=1)
value_of_name = sample_instance.name
π€JPG
- [Django]-Programmatically saving image to Django ImageField
- [Django]-Django South β table already exists
- [Django]-With DEBUG=False, how can I log django exceptions to a log file
0π
If you want to access it somewhere outside the model You can get it after making an object the Model. Using like this
OUSIDE THE MODEL CLAA:
myModal = MyModel.objects.all()
print(myModel.field_object)
USING INSIDE MODEL CLASS
If youβre using it inside class you can simply get it like this
print(self.field_object)
π€root
- [Django]-How do I use django rest framework to send a file in response?
- [Django]-How to find pg_config path
- [Django]-Sorting related items in a Django template
0π
Here is another solution to return the nth field of a model where all you know is the Modelβs name. In the below solution the [1] field is the field after pk/id.
model_obj = Model.objects.get(pk=pk)
field_name = model_obj._meta.fields[1].name
object_field_value = getattr(model_obj, field_name)
π€JessicaRyan
- [Django]-Django Unique Together (with foreign keys)
- [Django]-How to drop all tables from the database with manage.py CLI in Django?
- [Django]-How can I get tox and poetry to work together to support testing multiple versions of a Python dependency?
Source:stackexchange.com