Thursday, August 31, 2017

Re: Weird date math bug?



On Aug 31, 2017 9:44 PM, "Lachlan Musicman" <datakid@gmail.com> wrote:
Sorry, let me start again:


Yay, I'm not the only one that does it! Lol...

<snip>



class ChemoRegime(models.Model):
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
    chemotype = models.ForeignKey(ChemoType, on_delete=models.CASCADE)
    start_date = models.DateField(null=True, blank=True)
    stop_date = models.DateField(null=True, blank=True)

    def regime_age(self):
        age = timezone.now().date() - self.stop_date
        return age.days

<snip>



But in the browser:

Exception Type:     TypeError
Exception Value:    

unsupported operand type(s) for -: 'datetime.date' and 'NoneType'

Exception Location:     ./patients/models.py in regime_age, line 95


line 95 is         age = timezone.now().date() - self.stop_date


What am I doing wrong?

cheers
L.

I'm guessing that ChemoRegime.regime_age() contains line 95.

ChemoRegime defines the stop_date field with null=True and blank=True. I'm guessing this is because patients may not have yet stopped treatment, so they have no stop_date.

With that in mind, self.stop_date may be None in Python (and Null in the DB). Subtracting None from a real datetime.date object is not supported.

Ensure that stop_date has a date value before doing date math with it.

-James

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciXMOY5Mx5C91e0sXasXKa-f5mCga%2BDtf29AtQDaL1sqUg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment