Django内部Join数据库查询

时间:2017-05-15 10:53:29

标签: django postgresql

您好我的项目中有3个模型,并希望对它们进行内部联接查询。

class Experiment(models.Model):
    experiment_id = models.AutoField(primary_key=True)
    experiment_name = models.CharField(max_length=500)

class DataFile(models.Model):
    file_id = models.AutoField(primary_key=True)
    file_name = models.CharField(max_length=500)
    experiment_id = models.IntegerField(blank=True, null=True)
    date = models.DateTimeField(blank=True)
    created_on = models.DateTimeField(auto_now_add=True)

class Analysis(models.Model):
    sample_name = models.CharField(max_length=500)
    file_id = models.IntegerField(blank=True, null=True)

我正在使用postgre和我正在尝试的查询

select experiment_name,ma.rt
FROM main_experiment me 
INNER JOIN main_datafile md 
ON me.experiment_id = md.experiment_id
INNER JOIN main_analysis ma
ON ma.file_id = md.file_id

我想使用实验ID提取所有样本名称 我试过了

Experiment.objects.filter(experiment_id__sample_name=18) 

和许多其他组合,但我总是得到以下错误。

不支持的查询' '对于AutoField或不允许在该字段上加入。

1 个答案:

答案 0 :(得分:0)

为什么不使用外键?如果您的模型看起来像;

class Experiment(models.Model):
    #experiment_id = models.AutoField(primary_key=True) # you don't need to add, django will do it for you.
    experiment_name = models.CharField(max_length=500)

class DataFile(models.Model):
    #file_id = models.AutoField(primary_key=True) # you don't need to add, django will do it for you.
    file_name = models.CharField(max_length=500)
    experiment = models.ForeignKey(Experiment, related_name="data_file")
    date = models.DateTimeField(blank=True)
    created_on = models.DateTimeField(auto_now_add=True)

class Analysis(models.Model):
    sample_name = models.CharField(max_length=500)
    data_file = models.ForeignKey(DataFile, related_name="analysis")

然后你可以这样做:

Experiment.objects.filter(data_file__analysis__sample_name= 18)