• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Reverse Look Up for Foreign Key using related_name in Django

Aniruddha Chaudhari/2085/0
Django

In the previous tutorial, we have seen OneToOneField in the Django model. In this tutorial, we will learn about the ForeignKey field in the Django model.

Let’s understand the foreign key concept first.

Foreign Key in Django Model

Consider we have two models- Author and Books. The author field in the Books’ model is borrowed from the Author’ model.

This is how we can achieve it using the foreign key.

Model Author

class Author(models.Model):
    author_name = models.CharField(max_length=120)

Model Books

class Books(models.Model):
    book_name = models.CharField(max_length=120)
    writen_by = models.ForeignKey(Author, on_delete=models.CASCADE, null=True)

With the ForeignKey, we can set the one-to-many relationship between the two models.

If we have the instance of the Books model, we can access the Author information very easily. This is called forward compatibility.

Hope you are aware of reading model data.

Suppose book is the instance of the model Books. We can access the author name of the books in the Django template as below.

{{ book.author.author_name }}

If you want to access the foreign key value in the Django views, you can use the “__” notation.

For example,

Books.objects.all().values('book_name', 'writen_by__author_name')

But what if you want to access the Books information from the Author instance? There is a special provision in Django to accomplish this so-called backward compatibility.

Reverse Look Up for Foreign Key (aka Backward Compatibility)

For example, we want to list down the name of all the books written by the specific author.

The simple way of doing is that, update ForeignKey field in the Books model by setting related_name parameter. Give it any suitable name (say authors)

class Books(models.Model):
    book_name = models.CharField(max_length=120)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, related_name="authors")

Note: If you are modifying the model, don’t forget to make the migration.

Now, with the instance of the Author model, we can access information in the Django template about the books s/he has written using related_name.

Let’s say the author is the instance of the Author model.

How to get the list of all the books written by the author?

 {{ author.authors.book_name.all }} 

One author can have multiple books written. So it will return the list of the books.

You can print all the book names written by the author.

{% for book in author.authors.book_name.all }}
    {{book.book_name}}
{% endfor %} 

Find the name of the First Book written by the author.

Use keyword first.

 {{ author.authors.book_name.first }}  

Find the name of the Last Book written by the author.

Use keyword last.

 {{ author.authors.book_name.last }}  

With this simple reverse look-up using related_name, accessing foreign key information has become very easy. Isn’t it?

Note: If you don’t set related_name, Django has default related_name i.e books_set.

This is all about Reverse Look Up for Foreign Key using related_name in Django. I hope, with this tutorial you have learnt about backward compatibility. If you have any doubts or questions to ask, write in the comment. Thank you!

Python Interview Questions eBook

Django
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Leave a Reply Cancel reply

Prerequisite for Django

Learn Python Basics

Django Tutorials

Why Django?

Django- Create Your First Project

Django- Adding CSS/Static Files

Django- Use/Load Static Files

Django- Create Form

Django- Create Input-Tags

Django- Display Message on Form Submit

Django- MultipleChoiceField in Form

Django- Read Model Data (order_by)

Django- Read First/Last Queryset Object

Django- Update Model Field

Django- Signals

Django- Create TextField in Form

Django- Add Model to Admin Site

Django- Customize Admin Site

Django- Understanding Model User

Django- Registration/Signup Form

Django- Form Layout with Widget-Tweaks

Django- OneToOneField in Model

Django- Foreign Key & Reverse Lookup

Django- Custom Template Filters

Django- Interactive Shell

Django- Social Login

Django- Deploy and Host [FREE] 🔥

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard