query foreign key table for list view in django

Und*_*ble 6 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 
Run Code Online (Sandbox Code Playgroud)

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.

Wil*_*sem 5

如果你给另一个model定义了一个ForeignKeywith name column,那么django会用name构造一个数据库列column_id来获取相关对象的主键。但是你可以使用.column来获取相关的对象(所以不是id,而是那个 的对应对象id)。

因此,您可以更改模板,例如:

<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>
Run Code Online (Sandbox Code Playgroud)

(当然,假设author有一个name字段)。

由于您在这里将获取所有作者对象,因此prefetch_related(..)在这种情况下对查询集执行 a 通常更有效:

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

    def get_queryset(self):
        return Article.objects..prefetch_related(
            'author'
        ).order_by('-created_at')
Run Code Online (Sandbox Code Playgroud)

因此,您可以调用.author任何Article 实例来获取Author与其相关的对象(例如获取该作者的属性、修改作者等)。