Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of a Django Model Field object

I got a model field object using field_object = MyModel._meta.get_field(field_name). How can I get the value (content) of the field object?

like image 256
HuLu ViCa Avatar asked Aug 18 '18 05:08

HuLu ViCa


People also ask

How to get get count/average/min/max values from model field in Django?

Get count, average, min, max values from model field using Django Aggregate. Django queries help to create, retrieve, update and delete objects. But sometimes we need to get summered values from the objects. Then a Simple solution is to use Django aggregate feature Here are simple examples of how to use aggregation. app/models.py.

How to get field value in Django queryset?

Here are the steps to get field value in Django queryset. Let us say you have an object User (id, name, age, gender). Let us say you want to extract value of name and age fields in your User object. Here is the python code to do it.

How to get all Department object values in Django?

Edit Employee model class source code in DjangoHelloWorld / dept_emp / models.py file and add the method get_dept_values . # use models.ManyToMany field's all () method to return all the Department objects that this employee belongs to. # remove the last ',' and return the value. 2. Call Above Model Method In Html Template Page.

What is a model in Django?

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table. Each model is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a database field.


2 Answers

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) 
like image 83
awesoon Avatar answered Sep 30 '22 15:09

awesoon


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
like image 20
JPG Avatar answered Sep 30 '22 14:09

JPG