开发者

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?


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.


There's some docs on it, but mostly we tend to find uses for django functions that are used internally, like _meta.fields or _meta.get_all_field_names(), _meta.get_field_by_name.

For me, these are best discovered via iPython and tab completion. Or the source.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜