[Answered ]-Why am i getting error of AttributeError at /admin/main/consultation/ 'NoneType' object has no attribute 'lastname'

1👍

You consultation has two nullable fields patient and doctor. This means that self.patikent and self.doctor are not per se a patient and doctor object, but can be None as well.

You thus should cover the case where you these fields are None:

class consultation(models.Model):
    patient = models.ForeignKey(patient ,null=True, on_delete=models.SET_NULL)
    doctor = models.ForeignKey(doctor ,null=True, on_delete=models.SET_NULL)
    diseaseinfo = models.OneToOneField(diseaseinfo, null=True, on_delete=models.SET_NULL)
    consultation_date = models.DateField()
    status = models.CharField(max_length = 20)

    def __str__(self):
        names = []
        if self.patient is not None:
            names.append(f'{self.patient.firstname} {self.patient.lastname}')
        if self.doctor is not None:
            names.append(f'Dr. {self.doctor.firstname} {self.doctor.lastname}')
        return ' - '.join(names)

It however looks odd that patient and doctor can be NULL in the first place. It means a consultation can have no patient and/or doctor?

Leave a comment