DRF串行器与链接表的反向关系

时间:2019-06-07 12:50:46

标签: django-rest-framework

我想找到由Gene.symbol过滤的给定基因的所有TargetedExperiments。 我对Python和DRF还是比较陌生,如果有明显的解决方案,或者我没有添加任何关键信息,我深表歉意。

我发现了很多示例,这些示例中的表是直接链接的,但没有一个链接表。我尝试在Gene表中使用“ through”,但随后按表的顺序进行了腌制。

型号

class Gene(models.Model):
    gene_id = models.AutoField(primary_key=True)
    ensembl_id = models.CharField(max_length=255, null=True, blank=True)
    symbol = models.CharField(max_length=255)
    synonyms = models.CharField(max_length=255, blank=True, null=True)
    description = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'gene'

class TargetedExperiment(models.Model):
    targeted_experiment_id = models.AutoField(primary_key=True)
    study = models.ForeignKey(Study, models.DO_NOTHING)
    sgrna_sequence = models.ForeignKey(SgrnaSequence, models.DO_NOTHING, blank=True, null=True)
    metric = models.ForeignKey(Metric, models.DO_NOTHING)
    sgrna_label = models.CharField(max_length=50, blank=True, null=True)
    sgrna_efficiency = models.CharField(max_length=255, default='0%')
    transgene = EnumField(choices=['Yes', 'No'],default='No')

    class Meta:
        managed = True
        db_table = 'targeted_experiment'


class TargetedExperimentGene(models.Model):
    targeted_experiment_gene_id = models.AutoField(primary_key=True)
    targeted_experiment = models.ForeignKey(TargetedExperiment, models.DO_NOTHING)
    gene = models.ForeignKey(Gene, models.DO_NOTHING)
    reported_name = models.CharField(max_length=255)

    class Meta:
        managed = True
        db_table = 'targeted_experiment_gene'
class GeneViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Gene.objects.all()
    serializer_class = GeneSerializer

序列化器

class GeneSerializer(base_serializer.ObjectSerializer):
  class Meta:
    model = Gene
    fields = '__all__'
    depth = 3

base_serializer(用''覆盖NULL)

from rest_framework import serializers

class ObjectSerializer(serializers.ModelSerializer):
    def to_representation(self, instance):
        data = super().to_representation(instance)
        return {key: ('' if data[key] is None else value) for key, value in data.items()}

0 个答案:

没有答案