Ed.
Ed.

Reputation: 4597

Programmatically identify django foreignkey links

Similar to the question I asked here, if I wanted to list all of the foreign key relationships from a model, is there a way to detect these relationships (forward and backward) automatically?

Specifically, if Model 1 reads

class Mdl_one(models.Model):
    name = models.CharField(max_length=30)

and Model 2 reads

class Mdl_two(models.Model):
    mdl_one = models.ForeignKey(Mdl_one)
    name = models.CharField(max_length=30)

Is there some meta command I can run from Mdl_one (like Model_one()._meta.one_to_many) that tells me that mdl_two has a one-to-many foreign key relationship with it? Simply that mdl_one and mdl_two can be connected, not necessarily that any two objects actually are?

Upvotes: 1

Views: 185

Answers (1)

dani herrera
dani herrera

Reputation: 51715

This is you are looking for:

yourModel._meta.get_all_related_objects()

Sample (Edited):

class Alumne(models.Model):
    id_alumne = models.AutoField(primary_key=True)
    grup = models.ForeignKey(Grup, db_column='id_grup')
    nom_alumne = models.CharField("Nom",max_length=240)
    cognom1alumne = models.CharField("Cognom1",max_length=240)
    cognom2alumne = models.CharField("Cognom2",max_length=240, blank=True)
    ...

class Expulsio(models.Model):                             <---!
    alumne = models.ForeignKey(Alumne, db_column='id_alumne')
    dia_expulsio = models.DateField(blank=True)
    ...


>>> from alumnes.models import Alumne as A
>>> for x in A._meta.get_all_related_objects():
...     print x.name
... 
horaris:alumneexclosdelhorari
presencia:controlassitencia
incidencies:entrevista
incidencies:expulsio                                      <---!
incidencies:incidencia
incidencies:incidenciadaula
seguimentTutorial:seguimenttutorial

Upvotes: 1

Related Questions