2👍
That is some magic done by the model’s metaclass. See, the model fields are defined as a Field
class (or its child, eg. FloatField
). But when you want to work with the instance of model, you dont want to have a FloatField
in the .score
property, you want to have the actual value there, right? And that is done by the ModelBase.__metaclass__
when the model’s instance is created.
Now when you are saving the value, it’s completely ok, that the type of score
is unicode
– let’s say you received the data via form, and all the data you receive are unicode
. The value is converted (and validated) when saving. Django looks what kind of data is expected (float), and it tries to convert the value. If that wont work, it will raise an exception. Otherwise the converted value will be stored.
so what you want to do with your save method is this:
def save(self, *args, **kwargs):
if self.pk: # the model has non-empty primary key, so it's in the db already
oldScore = Score.objects.get(self.pk)
if oldScore.score > float(self.score):
# old score was higher, dont do anything
return False
super(Score, self).save(*args, **kwargs)
return True