From 2130e4b6a48ce14d98058c94a6c6adb8bbda343b Mon Sep 17 00:00:00 2001 From: zxenia Date: Tue, 19 Apr 2022 23:52:08 -0400 Subject: [PATCH] annotate biosample queryset with phenopacket subject id --- chord_metadata_service/chord/export_cbio.py | 12 ++++++------ .../chord/tests/test_export_cbio.py | 4 +++- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/chord_metadata_service/chord/export_cbio.py b/chord_metadata_service/chord/export_cbio.py index eb158ded1..0413078af 100644 --- a/chord_metadata_service/chord/export_cbio.py +++ b/chord_metadata_service/chord/export_cbio.py @@ -1,6 +1,7 @@ import logging import csv from typing import TextIO, Callable +from django.db.models import F from .export_utils import ExportError @@ -56,7 +57,8 @@ def study_export(getPath: Callable[[str], str], dataset_id: str): # Export samples with open(getPath(SAMPLE_DATA_FILENAME), 'w') as file_sample: - sampl = pm.Biosample.objects.filter(phenopacket__table__ownership_record__dataset_id=dataset.identifier) + sampl = pm.Biosample.objects.filter(phenopacket__table__ownership_record__dataset_id=dataset.identifier)\ + .annotate(phenopacket_subject_id=F("phenopacket__subject")) sample_export(sampl, file_sample) with open(getPath(SAMPLE_META_FILENAME), 'w') as file_sample_meta: @@ -181,12 +183,10 @@ def sample_export(results, file_handle: TextIO): subject_id = None if sample.individual is not None: subject_id = sample.individual + elif sample.phenopacket_subject_id is not None: + subject_id = sample.phenopacket_subject_id else: - phnpkt = pm.Phenopacket.objects.filter(biosamples=sample).first() - if phnpkt.subject is not None: - subject_id = phnpkt.subject.id - else: - continue + continue sample_obj = { 'individual_id': subject_id, diff --git a/chord_metadata_service/chord/tests/test_export_cbio.py b/chord_metadata_service/chord/tests/test_export_cbio.py index f1b30a100..2e2909d58 100644 --- a/chord_metadata_service/chord/tests/test_export_cbio.py +++ b/chord_metadata_service/chord/tests/test_export_cbio.py @@ -3,6 +3,7 @@ from typing import Dict, TextIO from os import walk, path +from django.db.models import F from django.test import TestCase from chord_metadata_service.chord.export_cbio import ( @@ -158,7 +159,8 @@ def test_export_cbio_patient_data(self): break def test_export_cbio_sample_data(self): - samples = PhModel.Biosample.objects.filter(phenopacket=self.p) + samples = PhModel.Biosample.objects.filter(phenopacket=self.p)\ + .annotate(phenopacket_subject_id=F("phenopacket__subject")) with io.StringIO() as output: sample_export(samples, output) # Check header