开发者

Django - how to obtain all fields from model

Is there an easy way to obtain all the fields from a certain django model, even those set via a foreignkey or many to many field on an other relation?

Example:

class A(models.Model):
    some_number = models.IntegerField()

class B(models.Model):
    link_to_a = models.ForeignKey(A, related_name="link_to_b")
开发者_如何学C

Invoking the method for A would return id, some_number, link_to_b.


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


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...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜