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
Django’s ContentType framework is built for this. You can refer the docs here.
In your case,