views:

486

answers:

1

Hello, I am trying to obtain class information on a field inside a model, when I only know name of the field and name of the model (both plain strings). How is it possible?

I can load the model dynamically:

from django.db import models
model = models.get_model('myapp','mymodel')

Now I have field - 'myfield' - how can I get the class of that field?

If the field is relational - how to get related field?

Thanks a bunch!

+4  A: 

You can use _meta attribute of model to get field, and from field you can get relation info and much more e.g. i have a employee table which has foreign key to department table

In [1]: from django.db import models

In [2]: model = models.get_model('timeapp', 'Employee')

In [3]: dep_field = model._meta.get_field_by_name('department')

In [4]: dep_field[0].rel.field_name
Out[4]: 'id'

In [5]: dep_field[0].rel.to
Out[5]: <class 'timesite.timeapp.models.Department'>

model._meta.get_field_by_name('department') returns a tuple of which first is the field object , others are default value etc, you can play around and see what info you want.

Anurag Uniyal
yes, thank you get_field_by_name and other functions are defined in django/db/models/options.py (in v1.1.1)
Evgeny