Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an object's fields?

I'm making a function to convert a model object into a dictionary (and all foreignkeys into more dictionaries, recursively). I learned from a friend that I can get a model's fields by looking at obj._meta.fields, but I can't find documentation for this anywhere.

How do I get a model's fields? How can I interpret what one can find in the _meta class?

like image 372
Claudiu Avatar asked Mar 20 '11 21:03

Claudiu


People also ask

How do I find the field of an object?

Field. get(Object obj) method returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.

How do I get a list of fields from a list of objects?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.

What is field in Java?

A field is a class, interface, or enum with an associated value. Methods in the java. lang. reflect. Field class can retrieve information about the field, such as its name, type, modifiers, and annotations.


1 Answers

This seemed fairly interesting, so I went looking through the django.forms source, looking specifically for the ModelForm implementation. I figured a ModelForm would be quite good at introspecting a given instance, and it just so happens that there is a handy function available that may help you on your way.

>>> from django.forms.models import model_to_dict
>>> from django.contrib.auth.models import Group
>>> g = Group.objects.filter()[0]
>>> d = model_to_dict(g)
>>> d
{'permissions': [40, 41, 42, 46, 47, 48, 50, 43, 44, 45, 31, 32, 33, 34, 35, 36, 37, 38, 39], 'id': 1, 'name': u'Managers'}
>>> 

Understandably, the _meta attribute is undocumented because it is an internal implementation detail. I can't see it changing any time soon though, so it's probably relatively safe to use. You can probably use the model_to_dict function above as a starter for doing what you want to do. There shouldn't be much of a change. Be wary of reverse relations if you plan on recursively including models.

There may be another avenue you wish to investigate also. django-piston is a RESTful framework that declares several emitters that may be useful to you, particularly the BaseEmitter.construct() method. You should be able to quite easily define a DictionaryEmitter that you use for purposes other than RESTful serialization.

like image 147
Josh Smeaton Avatar answered Oct 05 '22 11:10

Josh Smeaton