DRF模型序列化器外键返回对象,而不是ID

时间:2019-12-04 03:12:51

标签: django serialization django-rest-framework

序列化外键对象时,我将获得对象ID而不是对象。非常感谢任何关于如何获取不包括PK的对象的建议。

输出:

"biosamples": [
                    {
                        "short_form": "BTO_0004725",
                        "label": "embryonic fibroblast",
                        "ontology": 1
                    }
                ],

型号:

class Biosample(models.Model):
    biosample_id = models.AutoField(primary_key=True)
    ontology     = models.ForeignKey('Ontology', models.DO_NOTHING, related_name='biosample_ontologies')
    short_form   = models.CharField(max_length=255, unique=True )
    label        = models.CharField(max_length=255)

    class Meta:
        managed = True
        db_table = 'biosample'

    def __str__(self):
        return self.label

class Ontology(models.Model):
    ontology_id     = models.AutoField(primary_key=True)
    name            = models.CharField(unique=True, max_length=255)
    short_name      = models.CharField(max_length=255)
    url             = models.CharField(max_length=255)
    base_url        = models.CharField(max_length=255)
    rest_base_url   = models.CharField(max_length=255)
    prefix          = models.CharField(max_length=255, unique=True)

    class Meta:
        managed = True
        db_table = 'ontology'

    def __str__(self):
        return self.name

序列化器:

class OntologieSerializer(base.ObjectSerializer):
    class Meta:
        model = Ontology
        fields = '__all__'

class BiosampleSerializer(base.ObjectSerializer):
    class Meta:
        model = Biosample
        fields = '__all__'

    ontology     = OntologieSerializer(hidden=['ontology_id'])

ObjectSerializer(数据是从电子表格中读取的,字符串必须为空才能加载):

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

谢谢!

1 个答案:

答案 0 :(得分:0)

缩进错误,本体在Meta类中结束

class BiosampleSerializer(base.ObjectSerializer):
    class Meta:
        model = Biosample
        fields = '__all__'
    #Culprit:
    ontology     = OntologieSerializer(hidden=['ontology_id'])