Frage

Good Afternoon,

I'd like to be able to display a returned value from a method that is in a foreign table (the template obj shares a one-many relationship):

models.py

class teacher(stuff):
    name = models.charfield()
    website = models.URLField()
    slug = models.SlugField(max_length=255, db_index=True, unique=True)

    def get_page_url(self):
        return reverse('teacher_page', args=[self.slug])


class homework(stuff):
    assignment = models.ForeignKey(teacher)
    due_date = models.DateField()
    other assignment stuff..

I pass the assignment object into my template, and can access it's attributes like so:

{{homework.due_date}}

but let us say I want to display the page of the teacher who has assigned the homework. I thought I should be able to access it like so:

<a href='{{homework.teacher_set.get_page_url}}'>teacher page</a>

But this just results in an attribute error.

How can I get the url?

NOTE: This example was written on the fly for the purpose of conveying the question only. No syntax trolls!

War es hilfreich?

Lösung

Since it is a forward relationship, you would just do

{{homework.assignment.get_page_url}}

Further, if you are looking for a reverse foreign key relationship, you would do

{{teacher.name}}

{% for homework in teacher.homework_set.all %}
    {{homework.due_date}}
{% endfor %}

because teacher.homework_set returns a Manager

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top