How to get object fields?

I make 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 the model fields by looking at obj._meta.fields , but I can not find the documentation for this anywhere.

How to get model fields? How can I interpret what can be found in the _meta class?

+7
source share
2 answers

This seemed pretty interesting, so I looked at the source django.forms, specifically designed to implement ModelForm. I thought ModelForm would do a good job of introspecting this instance, and it just happens that there is a handy feature that can help you along the 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'} >>> 

It’s clear that the _meta attribute _meta undocumented because this is an internal implementation detail. I do not see this changing anytime soon, so it is probably relatively safe to use. You can probably use the model_to_dict function above as a starter to do what you want to do. There should not be big changes. Be careful with reverse relationships if you plan recursively, including models.

There may be another aspect that you want to explore. django-piston is a RESTful framework that declares several emitters that may be useful to you, especially the BaseEmitter.construct() method. You should be able to easily define the DictionaryEmitter that you use for purposes other than RESTful serialization.

+9
source

There are some documents there , but mostly we tend to find use for django functions that are used internally, for example _meta.fields or _meta.get_all_field_names() , _meta.get_field_by_name .

For me, this is best opened using iPython and completing the tab. Or source.

+4
source

All Articles