【问题标题】:DRF model serializer foreign key return object, not IDDRF 模型序列化器外键返回对象,而不是 ID
【发布时间】:2019-12-04 03:12:51
【问题描述】:

当序列化外键对象时,我将获取对象 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()}

谢谢!

【问题讨论】:

    标签: django serialization django-rest-framework


    【解决方案1】:

    缩进错误,本体最终在类 Meta

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 2019-02-20
      相关资源
      最近更新 更多