[Answered ]-How to find foreign key meta data in Django

2👍

Given a model name as a string, I think the safest way to get the corresponding class is to use the contenttypes framework. Something like this should work, using your real app name:

from django.contrib.contenttypes.models import ContentType
ct = ContentType.objects.get(app_name='my_app_name', model='DatasetPvtdata3')
my_model = ct.model_class()

If you’re not using the content types framework, in theory you can get the model from globals() if you have imported the model into whatever module contains the lookup code, but I wouldn’t go that way unless I had to:

from my_app_name.models import DatasetPvtdata3 
my_model = globals().get('DatasetPvtdata3')

To get the field object, use my_model._meta.get_field_by_name('commodity'). That returns a tuple, of which the field is the first element.

Once you have the field, field.rel will be a class representing the relationship. field.rel.to will be the model that the FK is to (DatasetSctg – the class itself, not a string containing its name) and field.rel.field_name will be the to_field name (the string description).

0👍

I have such scenario. I have a list where I show fields from basic table and some other fields from Foreignkey-related tables.

And I need verbose names, information about null=True/False of the fields and so on.

I have found that for the basic table I can read

Model._meta.get_field('name').verbose_name

And for the fields located inside a related table:

Model._meta.get_field(<foreignkey>).target_field.model._meta.get_field('name').verbose_name

I don’t know if this is at least partially the answer for this question. However maybe it can be a help for somebody.

👤mirek

Leave a comment