[Answered ]-Django – how to obtain all fields from model

2👍

You can use the semi-documented, non-public API on the _meta property of a model class:

from myapp.models import A

for f in A._meta._fields():
    print f.name

(Note, there is an existing work-item in Django to document this API: http://code.djangoproject.com/ticket/12663 )

You’ll need to manually follow relations, though, and pull in their field names.

Relation fields will have a rel property:

from myapp.models import A

for f in A._meta._fields():
    print f.name

    if hasattr(f, 'rel'):
        print "Grab more fields from " + rel.to.name
        g in rel.to._meta._fields():
            print g.name

0👍

Look in the very undocumented A._meta.fields:

foreignkeys = [f for f in A._meta.fields if f.attname.endswith(‘_id’)]

The fields have many interesting methods you’ll have to discover by using dir() or reading the source…

Leave a comment