0

In Django I have some model let's say:

class Learner(models.Model):  
    birth_date = models.DateField(null=True, blank=True)

def is_of_age(self):
    logging.debug(type(self.birth_date))
    .....

and view, let's say:

def overview(request):
    learner = Learner.objects.get(.....)
    logging.debug(type(learner.birth_date))
    .....

Why type of birth_date differs? In model's method it's <class 'dict'>, while in view it's <class 'datetime.date'>.

Michał Werner
  • 285
  • 4
  • 10

1 Answers1

0

Model fields are not automatically converted to the correct python type when assigning a value - only to the correct database type when they are saved. Django makes no guarantee on the type of birth_date whatsoever, except for some special fields that work with descriptors (think ForeignKey etc.).

Data retrieved from the database is converted to a Python type in a consistent manner. I honestly don't know if it is always the same type, but for the same data it will be consistent. That's about the only guarantee you'll get.

This becomes even more apparent with a BooleanField. Consider the following simple model:

class Learner(models.Model):
    is_of_age = models.BooleanField(blank=True)

The following demonstrates this behaviour:

>>> learner = Learner(is_of_age='yes he is')
>>> learner.save()
>>> learner.is_of_age
'yes he is'
>>> Learner.objects.get(pk=learner.pk).is_of_age
True
knbk
  • 52,111
  • 9
  • 124
  • 122