Description of the problem
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.
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"
}
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.
What I have tried
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?
Other software developers in the field of Bioinformatics might be interested in a solution of this problem, so I post here my approach as suggested by Alasdair.
The goal is to create a model for a living species, for the sake of simplicity let's say an animal, and create an endpoint with Django REST Framework representing the correct taxonomic ranks.
models.py
serializers.py
The method
to_representation
helps us to manipulate the output. I have put some extra work here to get the taxonomic ranks in the desired order.Thus for the red fox the output looks like this:
Red fox (Vulpes vulpes)
It is a simplified example and in reality you'd have many more fields or possibly a model for every taxonomic rank, but somewhere you might come across the conflict between the reserved word
class
and the taxonomic rank class.I hope this can help other people too.
You can do it like below
As explained in below answer
https://stackoverflow.com/a/47717441/2830850
You can rename field in the overloaded version of
get_fields()
method