Leszek Wroński Leszek Wroński - 10 months ago 41
Python Question

(Django 1.10) referring to properties of an object referred to by ForeignKey

In my app each object Kurs needs to have a field 'prowadzacy' specifying the user to which the given Kurs belongs. Therefore, my models.py has the following:

class Kurs(models.Model):
prowadzacy = models.ForeignKey(User)

I also need to know the first name of the user in possession of the given Kurs. In shell, the following works:

>>> k=Kurs.objects.get(id=1)
>>> k
<Kurs: Wprowadzenie do epi 2>
>>> k.prowadzacy
<User: leszekwronski>
>>> k.prowadzacy.first_name

Eventually I need to have a field in my Kurs object containing an outcome of a procedure transforming the possessor's first and last names.
As a first step, I want to add a field containing just the first name. However, when I modify my models.py to contain the following:

class Kurs(models.Model):
prowadzacy = models.ForeignKey(User)
imie = prowadzacy.first_name

then I get the following error:

AttributeError: 'ForeignKey' object has no attribute 'first_name'

I tried using 'self.prowadzacy.first_name' instead of just 'prowadzacy.first_name', but to no avail:

NameError: name 'self' is not defined

What am I doing wrong? After reading this I suspect that I cannot refer to the name of a field in a model until the definition of that particular model is finished. However, 1) I'm not sure and would be grateful for a decisive 'yes' or 'no' and 2) if that's the case, how I can refer to "the first name of the particular user which is the value of a different field in the model I am defining now"?

Answer Source

A "procedure" means a method. If you want your Kurs model to be able to display the full user name, write a method to do it.

class Kurs(models.Model):
     def full_user_name(self):
          return u'{} {}'.format(self.prowadzacy.first_name, self.prowadzacy.last_name)