Django连接不同的表

时间:2019-07-09 20:07:14

标签: django django-models

这就是我在模型中得到的

class SFE(models.Model):
snpid = models.ForeignKey(Snps, models.DO_NOTHING, db_column='SNPID', primary_key=True)  # Field name made lowercase.
elementid = models.ForeignKey(Functionalelement, models.DO_NOTHING, db_column='ElementID')  # Field name made lowercase.
celllineid = models.ForeignKey(Celllines, models.DO_NOTHING, db_column='CELLLINEID')  # Field name made lowercase.
countexperiments = models.PositiveIntegerField(db_column='countExperiments')  # Field name made lowercase.
filetype = models.CharField(db_column='fileType', max_length=10)  # Field name made lowercase.

class Meta:
    managed = False
    db_table = 'SNPs_FunctionalElement'
    unique_together = (('snpid', 'elementid', 'celllineid', 'filetype'),)

def __str__(self):
    return str(str(self.snpid) + str(self.elementid) + str(self.celllineid) + str(self.filetype))

class Functionalelement(models.Model):
elementid = models.AutoField(db_column='ElementID', primary_key=True)  # Field name made lowercase.
name = models.CharField(unique=True, max_length=55)

class Meta:
    managed = False
    db_table = 'FunctionalElement'

def __str__(self):
    return str(self.elementid)

class Snps(models.Model):
snpid = models.AutoField(db_column='SNPID', primary_key=True)  # Field name made lowercase.
rsid = models.CharField(unique=True, max_length=20)
chrom = models.CharField(max_length=5)
pos = models.PositiveIntegerField()
ref = models.CharField(max_length=1)
alt = models.CharField(max_length=1)
maf1000genomes = models.FloatField(blank=True, null=True)
maftopmed = models.FloatField(db_column='mafTOPMed', blank=True, null=True)  # Field name made lowercase.

class Meta:
    managed = False
    db_table = 'SNPs'

def __str__(self):
    return str(self.snpid)

现在,我想将FunctionalElement与SFE结合起来,以便在给定特定SFE.snpid的情况下检索字段FunctionalElement.name。

我尝试过SFE.objects.select_related('elementid__name'),但是我知道这是错误的,我不知道如何使用django ORM。

1 个答案:

答案 0 :(得分:0)

要获得一个简单的对象,您需要执行以下操作:a = SFE.objects.get(snpid=THE_SPECIFICSNPID)之后,您可以访问所有相关的对象,例如:a.elementid.name将返回您想要的内容。 Django ORM为您检索对象,这是因为“繁琐的加载”。这意味着,如果以后需要相关对象,Django将会为您获取它,当然,它需要执行另一个查询,并避免您需要调用方法select_related

总结: 要获取名称,您可以执行以下操作:

name = SFE.objects.get(snpid=THE_SPECIFICSNPID).select_related('elementid').elementid.name

应该可以