使用保留字"class"来表示.在Django和Django REST Framework中作为字段名称 [英] Using the reserved word "class" as field name in Django and Django REST Framework

查看:111
本文介绍了使用保留字"class"来表示.在Django和Django REST Framework中作为字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

分类学是一门基于共有特征来定义和命名生物有机体的科学.将有机体分类为分类群(单数:分类群),然后将这些分类分类.现代使用的主要等级是领域,王国,门,阶级,秩序,家庭,属和物种. 有关 Taxonomy

Taxonomy is the science of defining and naming groups of biological organisms on the basis of shared characteristics. Organisms are grouped together into taxa (singular: taxon) and these groups are given a taxonomic rank. The principal ranks in modern use are domain, kingdom, phylum, class, order, family, genus and species. More information on Taxonomy and Taxonomic ranks in Wikipedia.

Wikipedia 中文章 Taxonomic rank 中的 red fox 示例为例,我需要创建一个如下的JSON输出:

Following the example for the red fox in the article Taxonomic rank in Wikipedia I need to create a JSON output like this:

{
    "species": "vulpes",
    "genus": "Vulpes",
    "family": "Canidae",
    "order": "Carnivora",
    "class": "Mammalia",
    "phylum": "Chordata",
    "kingdom": "Animalia",
    "domain": "Eukarya"
}

由于Django REST Framework根据字段名称创建密钥,因此分类等级 class (在示例中为粗体)会引起问题,因为它是Python中的保留字,不能用作变量名.

Since Django REST Framework creates the keys based on the field names, the problem arises with the taxonomic rank class (bold in the example) as it is a reserved word in Python and can't be used as a variable name.

在Django中创建的模型类如下所示:

A model class created in Django would look like this:

class Species(models.Model):
    species = models.CharField()
    genus = models.CharField()
    family = models.CharField()
    # class = models.CharField() - class is reserved word in Python
    # class_ = models.CharField() - Django doesn't allow field names
    # ending with underscore. That wouldn't be either a satisfying solution.
    # further fields

问题

有没有可能解决此问题并生成所需输出的方法? 如果没有,解决此问题的最佳实践是什么?

Question

Is there any possible way to solve this problem and generate the desired output? If not, what is the best practice to work around this problem?

推荐答案

您可以按照以下步骤进行操作

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")

如以下答案所述

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

这篇关于使用保留字"class"来表示.在Django和Django REST Framework中作为字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆