Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 .

like image 958
Moon Avatar asked Oct 02 '19 16:10

Moon


People also ask

How does ForeignKey work in Django?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases. ForeignKey is defined within the django. db. models.

How do I access Django templates?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

What does {{ NAME }} this mean in Django templates?

8. What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.


1 Answers

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.

like image 84
nigel222 Avatar answered Oct 13 '22 21:10

nigel222