0

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!

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so so much! I believe that calculates the age (which is what I asked for so I will accept the answer) Can I also ask, it does not show the age when I go to Results in Django-admin, do you know how to make age show up as an already-filled-in field in Django-admin (if that made any sense)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.