What's the best way to auto convert a model field values before it is rendered?

122 views
Skip to first unread message

Vince

unread,
Apr 26, 2016, 5:43:51 PM4/26/16
to Django users
I need to store and retrieve temperatures in a model.  I'd like to store all the values in celsius.  However some users prefer to view the value in fahrenheit.
What is the recommended way to setup a model like this?  

Perhaps manually convert the values in the view and on save?
Or is it possible to use python properties in a model for saves, updates and gets? 
Or is some other practice preferred?

class Temp(models.Model):
    user = models.ForeignKey(User, unique=False)
    temperature = models.FloatField(null=True, blank=True)




jorr...@gmail.com

unread,
Apr 26, 2016, 10:13:53 PM4/26/16
to Django users
Do you need to do actual math with the converted values, or is it just a matter of displaying the original value as the converted value in the template to those users who prefer seeing Fahrenheit? In the latter case all you would have to do is create a custom template tag that takes the original value and displays it as Fahrenheit.

Derek

unread,
May 3, 2016, 10:34:20 AM5/3/16
to Django users
I would add it as a custom model method - see: https://docs.djangoproject.com/es/1.9/topics/db/models/#model-methods

So, for example:

class Temperature(models.Model):
    user = models.ForeignKey(User, unique=False)
    celcius = models.FloatField(null=True, blank=True)
   
    def _get_fahrenheit(self):
        "Returns the temperature in Fahrenheit."
        return '%s' % (self.celcius * 1.8 + 32.0)
    fahrenheit = property(_get_fahrenheit)

Derek

unread,
May 5, 2016, 4:40:03 AM5/5/16
to Django users
The '_get_fahrenheit()' method will also need to handle the case of a null entry for the 'celcius' field.
Reply all
Reply to author
Forward
0 new messages