以编程方式识别Django Foreignkey链接 [英] 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?
具体来说,如果Model 1读取
Specifically, if Model 1 reads
class Mdl_one(models.Model):
name = models.CharField(max_length=30)
和Model 2读取
class Mdl_two(models.Model):
mdl_one = models.ForeignKey(Mdl_one)
name = models.CharField(max_length=30)
是否可以从Mdl_one运行一些元命令(例如Model_one()._ meta.one_to_many),告诉我mdl_two与它具有一对多的外键关系?简单地说,可以连接mdl_one和mdl_two ,不一定必须实际上有两个对象都是 ?
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?
推荐答案
这是您正在寻找的东西:
This is you are looking for:
yourModel._meta.get_all_related_objects()
示例(已编辑):
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
这篇关于以编程方式识别Django Foreignkey链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!