Nora
Nora

Reputation: 1893

ProgrammingError in Django: object has no attribute, even though attribute is in object

I am working in Django, and have a model that needs to contain the field "age" (seen below)

class Result(models.Model):

    group = models.ForeignKey(Group, null=True)    
    lifter = models.ForeignKey("Lifter", null=True)    
    body_weight = models.FloatField(verbose_name='Kroppsvekt', null=True)
    age_group = models.CharField(max_length=20, verbose_name='Kategori', 
    choices=AgeGroup.choices(), null=True)
    weight_class = models.CharField(max_length=10, verbose_name='Vektklasse', 
    null=True)
    age = calculate_age(lifter.birth_date)
    total_lift = models.IntegerField(verbose_name='Total poeng',
                                 blank=True, null=True) 

The age is calculated with a method in utils.py, called "calculate_age":

def calculate_age(born):
    today = date.today()
    return today.year - born.year((today.month, today.day 
    < (born.month,born.day))

The lifter.birth_date passed to the calculate_age method comes from this model (in the same class as the Result-model)

class Lifter(Person):

    birth_date = models.DateField(verbose_name='Fødselsdato', null=True)
    gender = models.CharField(max_length=10, verbose_name='Kjønn', 
    choices=Gender.choices(), null=True)

However, I get the error 'ForeignKey' object has no attribute "birth_date". I have tried tweaking the code to get rid of it, but nothing seems to be working.

Does anyone know why I might be getting this error?

Thank you for your time!

Upvotes: 0

Views: 233

Answers (1)

Sayse
Sayse

Reputation: 43330

You cannot initialise a field like this, you are trying to initialize it by accessing the value of an instance of the class before it has even been declared.

Judging by your usage, you can just make it a property

change

age = calculate_age(lifter.birth_date)

to

@property
def age(self):
    return calculate_age(self.lifter.birth_date)

Upvotes: 2

Related Questions