Django Model - special characters in field name

Viewed 198

I'm creating model for my app. Unfortunately I'm working with measurements units like km/h, kg CO2/ton, heat content (HHV) - 30 different units at all. I don't know how to save it properly in django model or maybe in serializer to make it display proper unit name, including "/", " ", "(" in REST Responses. Also I will be importing data through django-import-export module so it should recognize excel columns which will be named like actual unit name. For example:

class Units(models.Model):
     km_h = models.FloatField(default=-1, null=True)
     kg_co2ton = models.FloatField(default=-1, null=True)

and I would like to have this data available in the following form:

class Units(models.Model):
     km/h = models.FloatField(default=-1, null=True)
     kg co2/ton = models.FloatField(default=-1, null=True)

How to write model and/or serializer to make it work and look good?

1 Answers

For django-import-export, you can use the column_name of the Field class to declare the column name to match your Excel import spreadsheet:

class UnitsResource(resources.ModelResource):
    km_h = Field(attribute='km_h', column_name='km/h')
Related