yegle
yegle

Reputation: 5865

Django:how to access to ForeignKey's model?

I need to access to ForeignKey's model of a given model.

Here's the sample code:

class modelA(models.db):
    field1 = models.ForeignKey('modelB')
class modelB(models.db):
    pass
## below is the pseudo code
modelA.get_model_of_fk('field1').objects.all() # fetch all objects of modelB

Of course it will be so easy if there's an instance of modelA involved. But I just can't find a way to do it without creating an instance of modelA.

My current solution:

instance_of_a = modelA.objects.all()[0]
model_b = instance_of_a.field1.__class__
model_b.objects.all() # fetch all objects of modelB

Upvotes: 1

Views: 526

Answers (2)

zsquare
zsquare

Reputation: 10146

Django's ContentType framework is built for this. You can refer the docs here.

In your case,

from django.contrib.contenttypes.models import ContentType
model_type = ContentType.objects.get_for_model(modelA.field1)
model_type.model_class().objects.all() # this will get you all objects of the foreign key model

Upvotes: 3

yegle
yegle

Reputation: 5865

I realized that, django itself must know what model a ForeignKey field links to, so I dug into django's source code and find this seems works:

modelA.field1.field.rel.to.objects.all() # same as modelB.objects.all()

Upvotes: 0

Related Questions