Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query foreign key table for list view in django

Tags:

python

django

I am very new to django. I have a django installation and am trying to create a UI in django for a few of the database tables.

In my database there are two tables - Articles and Author. The Articles table has a foreign key to Author table with field name as author_id.

I have managed to create a ListView class that lists articles. The code is like this:

from .models import Article

class ArticleListView(ListView):
    template_name = "article.html"
    context_object_name = 'articles'
    paginate_by = 25

    def get_queryset(self):
        queryset = Article.objects.all().order_by('-created_at')
        return queryset 

Then in the view I loop the Article queryset and prints its fields, and this works fine. However I am not sure how to query the corresponding Author table in order to get the author name and details. Can anyone please help me understand how this can be done? I read a lot of documentation/tutorials about this but I am unable to wrap my head around how to do this. Any help is very much appreciated.

Please note: The Article model was written by earlier django programmer.

like image 491
Undefined Variable Avatar asked May 25 '18 19:05

Undefined Variable


1 Answers

If you define a ForeignKey with name column to another model, then Django will construct a database column with the name column_id to obtain the primary key of the related object. But you can use .column to obtain the related object (so not the id, but the corresponding object of that id).

You can thus change the template, for example to:

<h1>Articles</h1>
<ul>
{% for article in object_list %}
    <li>{{ article.pub_date|date }} - {{ article.headline }}
         - {{article.author.name}}</li>
{% empty %}
    <li>No articles yet.</li>
{% endfor %}
</ul>

(given of course an author has a name field).

Since you here will fetch all the author objects, it is usually more efficient to do a prefetch_related(..) on the queryset in that case:

class ArticleListView(ListView):
    template_name = 'article.html'
    paginate_by = 25

    def get_queryset(self):
        return Article.objects..prefetch_related(
            'author'
        ).order_by('-created_at')

You can thus call .author on any Article instance to obtain the Author object that relates to it (and for instance fetch properties of that author, modify the author, etc.).

like image 169
Willem Van Onsem Avatar answered Nov 13 '22 12:11

Willem Van Onsem