How to use Foreign key Table attribute in Django Templates

There are many posts and StackOverflow which cover the answer to this question but most of them just show one way of accessing the foreign key table attributes inside templates.

Let’s consider these two models :

class Post(models.Model):
post_id = models.AutoField(primary_key=True)
post_title = models.CharField(max_length=50)
post_description = models.TextField()
post_date = models.DateTimeField(auto_now=True)

def __str__(self):
return self.post_title
class Like(models.Model):
like_id = models.AutoField(primary_key=True)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
preview = models.CharField(max_length=50)

Now let’s say we want to access the preview of a post from the Post class object. To do this the first we fetch all the Post class objects.

posts = Post.objects.all()

Now inside a template, you could do something like this to access the preview field data without using one more ‘for’ loop.

{% for post in posts %}
<li>{{ post.like_set.get.preview }}</li>
{% endfor %}

Here the important thing to note is that you could also use related_name and replace it with ‘like_set’ to get the same output.

Now let’s say we want to access the Post class fields from Like Class objects. The simplest way to do this is :

{% for like in likes %}
<li>{{ }}</li>
{% endfor %}

In this kind of relationship, you don’t need the related name or anything else you simply make the query using the name of that class in lowercase letters.

I hope you got what you have come for :)



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jack Sparrow

Web Developer + Android Developer + Traveller along with all this i love to tinker with new technology.