Using the reserved word “class” as field name in Django and Django REST Framework

后端 未结 3 599
慢半拍i
慢半拍i 2020-12-06 11:37

Description of the problem

Taxonomy is the science of defining and naming groups of biological organisms on the basis of shared characteristics. Organisms are grou

3条回答
  •  无人及你
    2020-12-06 12:26

    You can do it like below

    class SpeciesSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = Species
            fields = (
                'url', 'id', 'canonical_name', 'slug',  'species', 'genus',
                'subfamily', 'family', 'order','class', 'phylum',
                'ncbi_id', 'ncbi_taxonomy',
            )
            read_only_fields = ('slug',)
            extra_kwargs = {
                'url': {'lookup_field': 'slug'}
            }
    
    SpeciesSerializer._declared_fields["class"] = serializers.CharField(source="class_name")
    

    As explained in below answer

    https://stackoverflow.com/a/47717441/2830850

提交回复
热议问题