views:

37

answers:

2

Hi all,

how can I iterate and retrieve all fields of a django model?

I know that foo.item._meta.get_all_field_names() brings me all field names. How can I access those fields (incl. their actual values) on a model instance? (Except the normal notation foo.fieldname).

I need this in order to build a custom output for my model including its manyTomany relations. Any ideas?

+2  A: 

How about:

getattr(foo.__class__, <field_name>)

This should give you the field object, rather than the value in the given model instance. If you want the value of the field in the given model insance you can call it like this:

getattr(foo, <field_name>)
gruszczy
As you have mentioned yourself, this only returns me the field object. I need the fields value of the given model instance. Edited question accordingly...
Michael S
I've edited the answer, hope this helps.
gruszczy
+1  A: 

This looks ugly but it will work:

for each in model_instance._meta.fields: 
    print each.value_from_object(model_instance)

That said, I have another suggestion. Given that your requirement is to

to build a custom output for my model including its manyTomany relations.

how about serializing the instance to a suitable format (XML/JSON) and then working on that? this avoids any dependency on _meta or any of the internal methods (which can possibly change).

Manoj Govindan
Manoj thanks for your additions. The ugly one still does not solve the problem of my ManyToMany relations :( I guess I will have to go for serialization!
Michael S