[Answered ]-Django how to add query results foreign key model to queryset

1👍

Remove the for loop. then add the following line after the original_queryset = B.objects.filter(name=book) line->

queryset = original_queryset.author

If this doesn’t work then let me know. I hope I can help you.

You can rename your B model’s author field to authors, that makes your code more meaningful because ForeignKey field can store many data. In your code, you have made your B model’s author field as a ForeignKey field, which means books can have multiple authors. You can see the django documentation of ForeignKey reference.
If you change as I told you then don’t forget to run migration(python manage.py makemigrations and python manage.py migrate command in your cmd) and change the line queryset = original_queryset.author to queryset = original_queryset.authors

Another approach

You can pass the original_queryset in the context of the template,(i.e: {'queryset':original_queryset }) then in your template.html, you can add tages like this:

{% for book in queryset %}
<ul>
{% for author in book.author %}
<li>author.name</li>
....
{% endfor %}
</ul>
{% endfor %} 

By doing these, you can place your books and authors in your template nicely. If it still shows error, message me, I hope I can help you.

Leave a comment