close

How to get the value of a Django Model Field object

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get the value of a Django Model Field object in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to get the value of a Django Model Field object?

  1. How to get the value of a Django Model Field object?

    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:

  2. get the value of a Django Model Field object

    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:

Method 1

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)

Method 2

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read