与我提出的问题类似,如果我想列出模型中的所有外键关系,是否有方法自动检测这些关系(向前和向后)?
具体来说,如果模型1显示
class Mdl_one(models.Model):
name = models.CharField(max_length=30)
模型2显示
class Mdl_two(models.Model):
mdl_one = models.ForeignKey(Mdl_one)
name = models.CharField(max_length=30)
有没有什么meta命令可以从mdlOne运行(比如Model_one().meta.one_to_many)来告诉我mdl2与它有一对多的外键关系?简单地说,mdl1和mdl2是可以连接的,不一定有任何两个对象是实际的吗?
最佳答案
这是你要找的:
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