Django Model Iteration Fields

How can I repeat and retrieve all fields of a django model?

I know that foo.item._meta.get_all_field_names()returns me all the field names. How can I access these fields (including their actual values) in a model instance? (Except for the normal designation foo.fieldname).

I need this to create custom output for my model, including its many relationships with Tomany. Any ideas?

+5
source share
2 answers

What about:

getattr(foo.__class__, <field_name>)

This should give you a field object, not a value in this instance of the model. If you want the field value in the given model to be like this, you can call it like this:

getattr(foo, <field_name>)
+8
source

, :

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

, . , -

, Tomany.

(XML/JSON), ? _meta ( ).

+2

All Articles