Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Foreign Key: get related model?

Is it possible to get the related model of a foreign key through the foreign key field itself?

For example, if I have 3 models:

class ModelA(models.Model)
    field1 = models.CharField(max_length=10)

class ModelB(models.Model)
    field1 = models.CharField(max_length=10)

class ModelC(models.Model)
    field1 = models.CharField(max_length=10)
    field2 = models.ForeignKey(ModelA)
    field3 = models.ForeignKey(ModelB)

and I want to do:

for field in ModelC._meta.fields:
    if field.get_internal_type() == "ForeignKey":
        #get the related model for field e.g. ModelA or ModelB

Is this possible using just the models themselves rather than instances of the models?

like image 411
PT114 Avatar asked Apr 27 '12 08:04

PT114


People also ask

How do you get a related name on Django?

The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set. Explanation: Illustration of related_name=”name” using an Example.

What is ForeignKey relationship in Django?

Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.

What is __ str __ In Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model.

Can a model have two foreign keys Django?

Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example), or you must explicitly specify the foreign keys Django should use for the relationship using ManyToManyField.


1 Answers

If ModelA has an FK field named "foo", then this is how you can get the related model:

ModelA._meta.get_field('foo').rel.to

With your code, it would look like:

for field in ModelC._meta.fields:
    if field.get_internal_type() == "ForeignKey":
        print field.rel.to

If found it out by using tab completion in the shell long ago, it still works. You might want to learn to use the shell to reverse engineer stuff like that.

Update for Django>=2.0 users

Syntax has changed. Use the below code to get the related model:

ModelA._meta.get_field('foo').related_model
like image 172
jpic Avatar answered Oct 18 '22 16:10

jpic