Programmatically identify django foreignkey links

六眼飞鱼酱① 提交于 2020-01-05 09:07:45

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/9151360/programmatically-identify-django-foreignkey-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!