Moon
Moon

Reputation: 4160

How to access foreign key table's data in Django templates?

I want to access foreign key table's data into django templates.

my code is as below.

class TutorialCategory(models.Model):
    tutorial_category = models.CharField(max_length=200)
    category_summary = models.CharField(max_length=200)
    category_slug = models.CharField(max_length=200, default=1)

class TutorialSeries(models.Model):
    tutorial_series = models.CharField(max_length=200)
    tutorial_category = models.ForeignKey(TutorialCategory, verbose_name="Category", on_delete=models.SET_DEFAULT)
    series_summary = models.CharField(max_length=200)


Tutorial_obj = TutorialSeries.objects.get(pk=1)
{{ Tutorial_obj.tutorial_series}}
{{Tutorial_obj.category_summary}} // Not able to access TutorialCategory

I have searched on SO also & found to use _set which I have used but still not able to access table.

Pls if anyone have suggestion pls guide me .

Upvotes: 5

Views: 7726

Answers (1)

nigel222
nigel222

Reputation: 8202

You want

{{Tutorial_obj.tutorial_category.category_summary}} 

Not sure if that was just a silly error or a misunderstanding of how it's supposed to work

BTW stick to the conventions: an instance really should be lower case tutorial or tutorial_obj if you insist.

Upvotes: 10

Related Questions